$(function() {
	addSequenceId = "";// 当前页面测试序列的id
	dataVersionCode = "";//当前测试序列的数据版本code
	sequenceData = [];// 通过ID获得新增序列的基本信息数据
	taskState = 0;// 当前任务的状态
	getSequenceId();// 拿到测试序列ID
	initButton(taskState);// 角色拥有按钮权限
	caseElements = [];// 当前选中的基本用例信息供绘图使用和判断当前点击选中元素显示外部参数使用
	elementTypes = [];// 画布中的元素类型
	basicTree();// 基本用例树加载
	testSequence();// 测试序列树加载
	caseSelectIndex = "1";// 当前选中的基本用例的下s标
	copyCaseSelectIndex = "1";// 当前选择要复制的基本用的s标
	sequenceInfo = [];// 存放测试序列内所有的信息供保存使用
	caseWidth = 145;// 缩略图中一个用例的宽度
	caseHeight = 35;// 缩略图中一个用例的高度
	trationLineData = null;// 信号机的数据
	sequenceEditBool = true;// 是否可以复制粘贴
	// 分支和循环控件的头填充颜色
	titleBackGround = '#222222';
	// 分支和循环控件的头文字颜色
	initFontColor = '#00AAAA';
	// 分支和循环控件的字样式
	initLabelStyle = '14px Arial';
	// 分支和循环控件宽度
	banchLoopWidth = 100;
	// 分支和循环控件的高度
	banchLoopTitleHeight = 30;
	banchLoopHeight = 55;
	// 条件控件下方矩形默认高度
	banchLoopBottomHeight = 25;
	//初始绘图的坐标
	initLocation = {x:15,y:15};
	// 控件与控件的间距
	betweenTool = 15;
	// 小矩形控件的高度
	rectHeight = 30;
	// 小矩形控件的宽度
	rectWidth = 80;
	// 容器控件中的条件的第一个位置
	conditionPostion = {
		x : 31,
		y : 4
	};
	// 条件控件之间的间隔
	conditionSpace = 23;
	//当前选择的子对象的父节点数据
	childToParentData = null;
	// 当前选择的图形的id
	selectTargetId = '';
	// 当前选择的图形的数据
	selectTargetData = null;
	//下拉框的数据数组
	selectAllListData = [];
	getSelectListData();
	//条件控件中数据项数据数组
	shuJuAllDataArray = [];
	//发车设定中列车类型的数据
	lclxArray = [];
	//运行组织文件id
	yxzzId = '';
	//保存失败的提示信息
	failMsg = '';
	//加载图片完成个数
	imgCount = 0;
	//设置当前数据版本的显示信息
	setDataVersion();
	//LKJ控件中根据软件类型存储文件的数据
	storeVersionByType = [];
	//循环标示
	imgXunHuan = new Image();
	imgXunHuan.src = '../../images/xunhuan.png';
	//分支标示
	imgFenZhi = new Image();
	imgFenZhi.src = '../../images/fenzhi.png';
	//条件控件
	imgTiaoJian = new Image();
	imgTiaoJian.src = '../../images/tiaojian.png';
	//引导箭头
	guideJianTou = new Image();
	guideJianTou.src = '../../images/jiantou.png';
	imgXunHuan.onload = function(){
		imgCount = imgCount+1;
		if(imgCount>=3){
			//获取条件控件中数据项的下拉切换时的数据状态信息
			getShuJuXiangMsg();
		}
	};
	console.log(addSequenceId);
	imgFenZhi.onload = function(){
		imgCount = imgCount+1;
		if(imgCount>=3){
			//获取条件控件中数据项的下拉切换时的数据状态信息
			getShuJuXiangMsg();
		}
	};
	imgTiaoJian.onload = function(){
		imgCount = imgCount+1;
		if(imgCount>=3){
			//获取条件控件中数据项的下拉切换时的数据状态信息
			getShuJuXiangMsg();
		}
	};
	baseCaseCanvas = document.getElementById("canvasId");
	context = baseCaseCanvas.getContext('2d');
	baseTDrawCanvas = new TDrawCanvas(baseCaseCanvas);
	canvasWidth = 1470;
	var windowWidth = window.innerWidth;
	var centerWidth = windowWidth - 200 - 20 -310 - 20;
	$("#canvasDiv").width(centerWidth);
	$('#canvasSeId').css('width', centerWidth);
	$("#contentCenter").width(centerWidth);
	window.onresize = function() {
		var windowWidth = window.innerWidth;
		var centerWidth = windowWidth - 200 - 20 -310 - 20;
		$("#canvasDiv").width(centerWidth);
		$('#canvasSeId').css('width', centerWidth);
		$("#contentCenter").width(centerWidth);
	};
	firstGetCanvaseWidth = false;// 获取绘图的初始值
	$("#canvasId").width(canvasWidth);
	$('#parameterBottom').css('width', canvasWidth - 95);
	baseCaseCanvas.width = canvasWidth;

	// 注册画布元素点击事件
	baseCaseCanvas.onmousedown = function(e) {
		canvasDownFun(e);
		context.clearRect(0, 0, baseCaseCanvas.width, baseCaseCanvas.height);
		for (var i = 0; i < caseElements.length; i++) {
			setDrawSize(caseElements[i]);
		}
		resetCanvasHeight();
		drawProcessChart(caseElements);
		canvasClick();
	};
	sltCanvas = document.getElementById("inline");// 缩略图canvas
	sltCanvas.width = 795;
	sltCanvas.height = 54;
	sltCanvas.onmousedown = canvasClicks;// 缩略图canvas画布内的点击事件
	sltTDrawCanvas = new TDrawCanvas(sltCanvas);
	sltCanvasCopyObj = [];
	sltCanvasSelectObj = [];
	clcikAddSequeceBool = false;// 是否为快捷键复制基本用例
	// 点击基本信息按钮，展示新建序列的基本信息
	$("#basicInformation").click(function() {
		showSequenceInfo();
	});
	$("#Audit").click(function() {
		auditSequence();
	});
	$("#submit").click(function() {
		submitSequence();
	});
	// 序列信息修改后的保存功能
	$("#save").click(function() {
		saveSequence();
	});
	// 删除序列中的某一个基本用例
	$("#delete").click(function() {
		deleteBaseCase();
	});
	// 定位
	$('#Positioning').click(function() {
		locationClickFun();
	});
	// 树状图tab切换效果
	accordion();
	currentAttributes = [];
	// 数据展示区域下方canvas坐标轴
	dataCanvas = document.getElementById("canvasT");
	dataCanvas.onmousedown = signlCanvasClick;
	dataTDrawCanvas = new TDrawCanvas(dataCanvas);
	// canvasT(dataCanvas);//绘制下方的坐标轴
	// signalMachine(dataCanvas);//绘制下方的坐标轴上的小信号机
	// showLineData(dataCanvas,"5406B09CE22E40A8ACCA712C4CA6A740","30040003");//郑州局数据
	// showLineData(dataCanvas,"66ACA0B09D044BFC92FD5CFF03E7B59C","183E0000");
	stroke = '#D6D6D4';

	// 滚动滚动条，动态改变绘图的大小
	$('#canvasDiv').on(
			'scroll',
			function(e) {
				if ($(this).scrollLeft() === 0) {
				}
				if (($(this).width() + $(this).scrollLeft()) >= $('#canvasId')
						.width()) {
					canvasWidth = canvasWidth + 10;
					$("#canvasId").width(canvasWidth);
					baseCaseCanvas.height = 750;
					baseCaseCanvas.width = canvasWidth;
					$('#parameterBottom').css('width', canvasWidth);
					
					context.clearRect(0, 0, baseCaseCanvas.width, baseCaseCanvas.height);
					for (var i = 0; i < caseElements.length; i++) {
						setDrawSize(caseElements[i]);
					}
					resetCanvasHeight();
					drawProcessChart(caseElements);
					canvasClick();
				}
			});
});// 入口函数结束

// 从测试序列界面的链接路径中截取ID
function getSequenceId() {
	var url = location.search; // 获取url中"?"符后的字串
	if (url.indexOf("?") != -1) {
		var str = url.substr(1);
		strs = str.split("&");
		if (strs.length >= 1) {
			addSequenceId = (strs[0].split('=')[1]);
		}
		if (strs.length >= 2) {
			taskState = (strs[1].split('=')[1]);
		}
		if (strs.length >= 3) {
			dataVersionCode = (strs[2].split('=')[1]);
		}
	}
}
// 根据ID查到整个序列的信息
function getSequenceData(addSequenceId) {
	$.ajax({
		url : '../../../sequence/querySequenceContentById',
		type : 'POST',
		data : {
			sequenceId : addSequenceId
		},
		success : function(data) {
			console.log(data);
			if (data.flag == 0) {
				sequenceData = data.content;// 拿到新增序列的信息数据
			} else {
				danger(data.errorInfo);
			}
		}
	});
}
function showSequenceInfo() {
	sequenceEditBool = false;// 屏蔽复制粘贴功能
	if (taskState == 0) {
		BootstrapDialog
				.show({
					title : '序列信息',
					message : $(
							"<form class='form-inline' style='height:360px'></form>")
							.load('sequenceAdd.html'),
					onshown : function() {
						sequenceMsgViewData();
					},
					buttons : [
							{
								icon : 'glyphicon glyphicon-check',
								label : '保存',
								cssClass : 'btn-primary',
								autospin : true,
								action : function(dialogRef) {
									var sequenceNum = $("#sequenceNumInAdd")
											.val();
									var sequenceDescribe = $(
											"#sequenceDescribeInAdd").val();
									var sequenceNumInAdd = $(
											"#sequenceNumInAdd").val();
									// 判断描述是否为空
									if (sequenceDescribe == "") {
										danger("测试序列描述不能为空!");
										return false;
									}
									// 判断描述过长
									if (sequenceDescribe.length >= 200) {
										danger("测试序列描述不能超过200个字符!");
										return false;
									}
									// 编号是否为空
									if (sequenceNumInAdd == "") {
										danger("测试序列编号不能为空!");
										return false;
									}
									// 编号过长
									if (sequenceNumInAdd.length >= 20) {
										danger("测试序列编号不能超过20个字符!");
										return false;
									}
									$
											.ajax({
												type : "POST",
												url : "../../../sequence/editSequence",
												dataType : "json",
												data : {
													"id" : sequenceData[0].SEQUENCE_ID,
													"code" : $(
															'#sequenceNumInAdd')
															.val(),
													"describe" : $(
															'#sequenceDescribeInAdd')
															.val()
												},
												success : function(data) {
													var flag = data.flag;
													if (flag == 0) {
														var content = "保存成功!";
														success(content);
														getSequenceData(sequenceData[0].SEQUENCE_ID);
													} else {
														var info = "<div style='color:black;'>"
																+ data.errorInfo
																+ "</div>";
														danger(info);
													}
												}
											});
									dialogRef.close();
									sequenceEditBool = true;// 释放复制粘贴功能
								}
							}, {
								label : '取消',
								action : function(dialogRef) {
									dialogRef.close();
									sequenceEditBool = true;// 释放复制粘贴功能
								}
							} ]
				});
	} else {
		BootstrapDialog.show({
			title : '序列信息',
			message : $(
					"<form class='form-inline' style='height:360px'></form>")
					.load('sequenceAdd.html'),
			onshown : function() {
				sequenceMsgViewData();
			}
		});
	}

}

function sequenceMsgViewData() {
	// 初始化各个值，只读不可修改
	$("#sequenceTypeInAdd").append(
			"<option value='" + sequenceData.sequenceType + "'>"
					+ sequenceData.sequenceTypeName + "</option>");
	$("#sequenceTypeInAdd")[0].disabled = true;
	$("#sequenceNameInAdd").val(sequenceData.sequenceName);
	$("#sequenceNameInAdd")[0].disabled = true;
	$("#sequenceNumInAdd").val(sequenceData.sequenceCode);
	$("#sequenceDescribeInAdd").val(sequenceData.describe);

	if (taskState == 0) {
		$("#sequenceNumInAdd")[0].disabled = false;
		$("#sequenceDescribeInAdd")[0].disabled = false;
	} else {
		$("#sequenceNumInAdd")[0].disabled = true;
		$("#sequenceDescribeInAdd")[0].disabled = true;
	}

	var wenArray = [ {
		id : "1",
		type : '9',
		text : '车载数据文件',
		divId : 'chezaiselect'
	}, {
		id : "1",
		type : '10',
		text : '运行组织文件',
		divId : 'yunxingselect'
	} ];
	for (var i = 0; i < wenArray.length; i++) {
		$("#" + wenArray[i].divId).append(
				getWenJianData(wenArray[i].id, wenArray[i].type));
	}

	$("#chezaiselect").find(
			"option[value=" + sequenceData.dataVersion + "]").attr(
			'selected', true);
	$("#yunxingselect").find(
			"option[value=" + sequenceData.yxjlVersion + "]").attr(
			'selected', true);

	$("#chezaiselect")[0].disabled = true;
	$("#yunxingselect")[0].disabled = true;
}

//
function getWenJianData(id, type) {
	var str = "";
	$.ajax({
		url : "../../../LKJSoftwareVersion/getVersionName",
		type : "post",
		data : {
			"sId" : id,
			"type" : type
		},
		dataType : "json",
		async : false,
		success : function(data) {
			if (data.flag == 0) {
				var content = data.content;
				str = ajaxOption(content);
			}
		},
		error : function() {
		}
	});
	return str;
}
// 将查询到的下拉内容组合放到对应的位置
function ajaxOption(content) {
	var str = "<option value=''></option>";
	if (content != "" && content != null) {
		for (var i = 0; i < content.length; i++) {
			str += "<option value=" + content[i].VERSION_ID + ">"
					+ content[i].VERSION_NAME + "</option>";
		}
		;
	}
	return str;
}
// 用例的基本信息审核
function auditSequence() {
	BootstrapDialog
			.show({
				title : '测试序列信息审核',
				message : $(
						"<form class='form-inline' style='height:300px'></form>")
						.load('baseCaseAudit.html'),
				onshown : function() {
					// 初始化各个值
					$("#auditResult")
							.append(
									"<option value='2'>审核通过</option><option value='3'>审核不通过</option>");
				},
				buttons : [
						{
							icon : 'glyphicon glyphicon-check',
							label : '确定',
							cssClass : 'btn-primary',
							autospin : true,
							action : function(dialogRef) {
								var auditResult = $("#auditResult").val();// 审核结果
								var auditOpinion = $("#caseAudit").val();// 审核意见
								var versionNow = $(
										"input[name='versionNow']:checked")
										.val();
								// 判断类型是否为空
								if (auditResult == "") {
									danger("请选择审核结果！");
									return false;
								}
								// 判断审核意见是否为空
								if (auditOpinion == "") {
									danger("审核意见不能为空!");
									return false;
								}
								/* ajax向后台发送新建用例的数据 */
								$
										.ajax({
											type : "POST",
											url : "../../../sequence/auditTestSequence",
											data : {
												"sequenceId" : addSequenceId,
												"result" : auditResult,
												"view" : auditOpinion,
												"versionNow" : versionNow
											},
											success : function(data) {
												var flag = data.flag;
												if (flag == 0) {
													initButton(auditResult);
													taskState = auditResult;
													var content = "序列审核成功!";
													success(content);
												} else {
													danger(data.errorInfo);
												}
											},
											error : function(err) {
												danger("服务器异常!");
											}
										});
							}
						}, {
							label : '取消',
							action : function(dialogRef) {
								dialogRef.close();
							}
						} ]
			});
}
// 修改后的信息提交
function submitSequence() {
	//检查当前测试序列保存时外部参数是否已经填写
	if(!checkAllCaseElements(sequenceInfo)){
		warning(failMsg);
		return;
	};
	BootstrapDialog.show({
		title : '测试序列信息提交',
		message : "确定提交此序列用例信息么？",
		buttons : [ {
			icon : 'glyphicon glyphicon-check',
			label : '确定',
			cssClass : 'btn-primary',
			autospin : true,
			action : function(dialogRef) {
				submitFun();// 点击提交前，先执行保存操作，保存成功后，再执行提交操作
			}
		}, {
			label : '取消',
			action : function(dialogRef) {
				dialogRef.close();
			}
		} ]
	});
}

// 点击提交前，先执行保存操作，保存成功后，再执行提交操作
function submitFun() {
	for(var i = 0;i<sequenceInfo.length;i++){
		sequenceInfo[i].caseContent=JSON.stringify(sequenceInfo[i].caseElement);
	}
	
	var saveSequenceArray = [].concat(JSON.parse(JSON.stringify(sequenceInfo)));
	for(var i = 0;i<saveSequenceArray.length;i++){
		saveSequenceArray[i].caseElement = [];
	}
	console.log(saveSequenceArray);
	$.ajax({/* ajax向后台发送提交测试序列信息 */
		type : "POST",
		url : "../../../sequence/addSequenceContent",
		data : {
			"sequenceId" : addSequenceId,// 序列ID 没有错误
			"sequenceContent" : JSON.stringify(saveSequenceArray)
		// 多个基本用例集合
		},// caseLists 封装存在问题
		success : function(data) {
			var flag = data.flag;
			if (flag == 0) {// 点击提交前，先执行保存操作，保存成功后，再执行提交操作
				/* ajax向后台发送提交测试序列信息 */
				$.ajax({
					type : "POST",
					url : "../../../sequence/submitTestSequence",
					data : {
						"sequenceId" : addSequenceId,
					},
					success : function(data) {
						var flag = data.flag;
						if (flag == 0) {
							initButton(1);
							BootstrapDialog.alert({
								title : '提示',
								message : "测试序列提交成功!",
								type : BootstrapDialog.TYPE_SUCCESS
							});
							setTimeout(function() {
								BootstrapDialog.closeAll();
							}, 800);
						} else if (flag == -1) {
							danger("服务器异常，测试序列提交失败!");
						}
					},
					error : function(err) {
						danger("服务器异常!");
					}
				});
			} else if (flag == -1) {
				danger("服务器异常，测试序列保存失败!");
			}
		},
		error : function(err) {
			danger("服务器异常!");
		}
	});
}
//根据序列信息快速生成自动测试任务
function addTask(){
	BootstrapDialog
		.show({
			size: BootstrapDialog.SIZE_WIDE,
			title: '快速创建测试任务',
			draggable: true,
			closable: false,
			message: $("<form style='height:200px;'></form>").load(
				'taskAdd.html'),
			onshown: initTestTask,
			buttons: [{
				icon: 'glyphicon glyphicon-remove',
				label: '取消',
				cssClass: 'btn-primary',
				autospin: true,
				action: function (dialogRef) {
					dialogRef.close();
				}
			}, {
				icon: 'glyphicon glyphicon-check',
				label: '确定',
				cssClass: 'btn-primary',
				autospin: true,
				action: function () {
					var testTaskName = $('#testTaskName').val(); //任务名称
					var taskDes = $('#taskDes').val().trim(); //任务描述
					if (testTaskName == "") {
						var content = "请输入测试任务名称！";
						warning(content);
					} else if (testTaskName.length >=25) {
						var content = "测试任务名称不能超过25个字符！";
						warning(content);
					}else if (taskDes == "") {
						var content = "请输入测试任务描述！";
						warning(content);
					} else if (taskDes.length >=50) {
						var content = "测试任务描述不能超过50个字符！";
						warning(content);
					} else {
						$.ajax({
							url: '../../../testTask/addTestTask',
							type: 'post',
							dataType: "json",
							data: {
								"testTaskName": testTaskName,
								"taskDes": taskDes,
								"nums": JSON.stringify(["1"]),
								"sequenceIds": JSON.stringify([sequenceData.sequenceId]),
								"platFormIds": JSON.stringify([""])
							},
							success: function (data) {
								var flag = data.flag;
								var taskId = data.content;
								if (flag == 0) {
									var content = "保存成功！";
									success(content);
									setTimeout(function () {
										BootstrapDialog.closeAll();
									}, 800);
									window.location.href = "../../test/html/autoTest.html?taskId=" + taskId + "&userName=" + "";
								} else {
									var content = "保存失败！";
									danger(content);
								}
							}
						});
					}

				}
			}]
		});

}

function initTestTask(){
	//sequenceData.sequenceName
	$("#testTaskName").val(sequenceData.sequenceName);
	$("#taskDes").val(sequenceData.describe);
}
// 保存序列信息
function saveSequence() {
	//检查当前测试序列保存时外部参数是否已经填写
	if(!checkAllCaseElements(sequenceInfo)){
		warning(failMsg);
		return;
	};
	var saveSequenceArray = [].concat(JSON.parse(JSON.stringify(sequenceInfo)));
	for(var i = 0;i<saveSequenceArray.length;i++){
		var copyArray = reSetSendData(saveSequenceArray[i].caseElement);
		saveSequenceArray[i].caseElement = copyArray;
	}
	for(var i = 0;i<saveSequenceArray.length;i++){
		saveSequenceArray[i].caseContent=JSON.stringify(saveSequenceArray[i].caseElement);
	}
	for(var i = 0;i<saveSequenceArray.length;i++){
		saveSequenceArray[i].caseElement = [];
	}
	console.log(sequenceInfo);
	console.log(saveSequenceArray);
	BootstrapDialog.show({
		title : '测试序列信息保存',
		message : "确定保存此序列用例信息么？",
		buttons : [ {
			icon : 'glyphicon glyphicon-check',
			label : '确定',
			cssClass : 'btn-primary',
			autospin : true,
			action : function(dialogRef) {
				$.ajax({/* ajax向后台发送提交测试序列信息 */
					type : "POST",
					url : "../../../sequence/addSequenceContent",
					data : {
						"sequenceId" : addSequenceId,// 序列ID 没有错误
						"sequenceContent" : JSON.stringify(saveSequenceArray)
					// 多个基本用例集合
					},// caseLists 封装存在问题
					success : function(data) {
						var flag = data.flag;
						if (flag == 0) {
							BootstrapDialog.alert({
								title : '提示',
								message : "测试序列保存成功!",
								type : BootstrapDialog.TYPE_SUCCESS
							});
							setTimeout(function() {
								BootstrapDialog.closeAll();
							}, 800);
						} else if (flag == -1) {
							danger("服务器异常，测试序列保存失败!");
						}
					},
					error : function(err) {
						danger("服务器异常!");
					}
				});
			}
		}, {
			label : '取消',
			action : function(dialogRef) {
				dialogRef.close();
			}
		} ]
	});
}
// 基本用例树信息获取
function basicTree() {
	// 查询基本用例树信息
	var setting = {
		view : {
			dblClickExpand : true,// 双击节点时，是否自动展开父节点的标识
			showLine : true,// 是否显示节点之间的连线
			addDiyDom: addDiyDom,
			fontCss : {
				'color' : 'black',
				'font-weight' : 'bold'
			},// 字体样式函数
			selectedMulti : false
		// 设置是否允许同时选中多个节点
		},
		check : {
			chkStyle : "checkbox",// 复选框类型
			enable : true
		// 每个节点上是否显示 CheckBox
		},
		data : {
			simpleData : {// 简单数据模式
				enable : true,
				idKey : "id",
				pIdKey : "pId",
				rootPId : ""
			}
		},
		// 当树中的子节点被双击时,获取到子节点对应的元素的id
		callback : {
			onDblClick : function(event, treeId, treeNode) {
				clcikAddSequeceBool = false;
				var caseId = treeNode.id;// 获取当前点击的基本用例的id
				var name = treeNode.name;
				if (!treeNode.isParent) {// 当点击的是子元素不是父元素时
					// if($("#save").attr("hidden")==undefined){//根据权限判断左侧的用例树点击是否有效
					getBaseCaseById(caseId, name);// 通过ID找到基本用例并绘制图形
					// }else{
					// return false;
					// }
				}
			}
		}
	};
	var treeNodes;
	$.ajax({
		async : false,// 是否异步
		cache : false,// 是否使用缓存
		type : 'POST',// 请求方式：post
		dataType : 'json',// 数据传输格式：json
		data : {pid:0,base:true},
		url : "../../../basecaseTree/queryBaseCaseTree",// 请求路径
		success : function(data) {
			if (data.flag == 0) {
				// 请求成功后处理函数
				treeNodes = data.content;// 所有表格内基本用例
				var t = $("#casetree");
				// 加载基本用例树信息
				t = $.fn.zTree.init(t, setting, treeNodes);
			} else {
				danger(data.errorInfo);
			}
		}
	});
}
function addDiyDom(treeId, treeNode) {
	var aObj = $("#" + treeNode.tId + "_ico");
	if ($("#diyBtn_"+treeNode.id).length>0||treeNode.isParent) return;
	var editStr = "";
	aObj.removeClass("button ico_docu");
	if(treeNode.type==0){//人工编辑
		editStr +="<img src='../../images/tree/bjyl_b.png' style='vertical-align: text-bottom;' alt=''/>"; 
	}else if(treeNode.type==1){//手工录制
		editStr +="<img src='../../images/tree/luzhi_b.png' style='vertical-align: text-bottom;' alt=''/>"; 
	}
	aObj.append(editStr);	
};
// 点击树状图内的基本用例时，向测试序列内添加基本用例功能
function getBaseCaseById(id, name) {
	$
			.ajax({
				url : '../../../basecase/getBaseCaseContentByCaseId',
				type : 'POST',
				data : {
					caseId : id
				// 基本用例的id
				},
				success : function(data) {
					console.log(data);
					if (data.flag == 0) {
						caseElements = JSON.parse(data.content);
						if (clcikAddSequeceBool) {// 是否为复制对象
							for (var i = 0; i < caseElements.length; i++) {
								for (var j = 0; j < caseElements[i].data.length; j++) {
									caseElements[i].data[j].value = sltCanvasCopyObj[caseSelectIndex - 1].caseElement[i].data[j].value;
									for (var k = 0; k < caseElements[i].children.length; k++) {
										for (var p = 0; p < caseElements[i].children[k].data.length; p++) {
											if (sltCanvasCopyObj[caseSelectIndex - 1].caseElement[i].children[k].data.length > 0) {
												caseElements[i].children[k].data[p].value = sltCanvasCopyObj[caseSelectIndex - 1].caseElement[i].children[k].data[p].value;
												caseElements[i].children[k].data[p].text = sltCanvasCopyObj[caseSelectIndex - 1].caseElement[i].children[k].data[p].text;
												caseElements[i].children[k].data[p].name = sltCanvasCopyObj[caseSelectIndex - 1].caseElement[i].children[k].data[p].name;
												caseElements[i].children[k].data[p].displayValue = sltCanvasCopyObj[caseSelectIndex - 1].caseElement[i].children[k].data[p].displayValue;
											}
										}
									}
								}
							}
						}
						clcikAddSequeceBool = false;
						console.log(caseElements);
						if (caseElements.length > 0) {
							caseElements[0].x = initLocation.x;
							caseElements[0].y = initLocation.y;
							
							//设置当前默认第一个控件为选中状态
							selectTargetId = caseElements[0].id;
							setSelectedById(selectTargetId);
							
							context.clearRect(0, 0, baseCaseCanvas.width,
									baseCaseCanvas.height);
							for (var i = 0; i < caseElements.length; i++) {
								setDrawSize(caseElements[i]);
							}
							resetCanvasHeight();
							// 初始化数据获取完成后，开始绘制图形
							drawProcessChart(caseElements);
							canvasClick();
							if ($("#save").attr("hidden") == undefined) {// 根据权限判断左侧的用例树点击是否有效
								var baseCase = {
									id : id,
									caseContent:JSON.stringify(caseElements),
									caseElement : caseElements,
									name : name
								};
								sequenceInfo.push(baseCase);// 放到缩略图数组中
							} else {
								var baseCase = {
									id : id,
									caseContent:JSON.stringify(caseElements),
									caseElement : caseElements,
									name : name
								};
								sequenceInfo = [];
								sequenceInfo.push(baseCase);// 放到缩略图数组中
							}

							caseSelectIndex = sequenceInfo.length + "";
							drawThumbnails(sltCanvas, sequenceInfo,
									caseSelectIndex,true);// 绘制点击的基本用例内的条件轴
							
						}
						if (caseElements.length) {// 将点击的基本用例加入到轮播图中
							for (var i = 0; i < sequenceInfo.length; i++) {
								$(".showBox ul").append(
										"<li>" + sequenceInfo[i].name
												+ "</li>");
							}
						}
						console.log();
					} else {
						danger(data.errorInfo);
					}
				}
			});
}

// 根据文件id和发车方向信息从后台解析出文件内容并绘制到画布中
function showLineData(canvase, id, drection) {
	$.ajax({
		url : '../../../sequence/getLineDataByDrection',
		type : 'POST',
		data : {
			fileId : id,// 文件id
			drectionNumber : drection
		},
		success : function(data) {
			var flag = data.flag;// 成功与否标志
			if (flag == 0) {
				var lineData = data.content;
				trationLineData = lineData;
				drawBasicData(canvase, lineData);
			} else {
				danger(data.errorInfo + "!");
			}
		}
	});

}
function drawBasicData(canvas, basicData) {
	var index = 20;
	var gap = 45;
	var width = (gap + 10) * basicData.length + 100;
	canvas.width = width;

	var context = canvas.getContext('2d');
	context.beginPath();
	context.strokeStyle = '#ffffff';
	context.moveTo(20, 110);
	context.lineTo(width, 110);
	context.stroke();
	context.closePath();
	var obj = null;
	for (var i = 0; i < basicData.length; i++) {
		if (basicData[i].type == 1) {
			obj = basicData[i];
			obj.dic = [];
		} else if (basicData[i].type == 2) {
			if (basicData[i].teleseme.type == 5) {
				obj.dic.push(basicData[i]);
			}
		}
	}
	var outBool = false;// 只绘制一个出站信号机
	for (var i = 0; i < basicData.length; i++) {

		if (basicData[i].type == 1) {
			outBool = true;
			index = drawTrainStation(index, gap, basicData[i].trainstation,
					canvas);
		} else if (basicData[i].type == 2) {
			if (basicData[i].teleseme.type != 5) {
				index = drawTeleseme(index, gap, basicData[i].teleseme, canvas);
			} else {
				if (outBool) {
					index = drawTeleseme(index, gap, basicData[i].teleseme,
							canvas);
					outBool = false;
				}
			}
		}
	}

}
// 在画布上绘制才车站信息
function drawTrainStation(index, gap, trainstation, canvas) {
	var name = trainstation.name;
	var x = index + gap;
	var trainStation = dataTDrawCanvas.getDrawing('trainStation', {
		name : name,
		x : x
	});
	trainStation.draw();

	for (var i = 0; i < trationLineData.length; i++) {
		if (trationLineData[i].type == 1) {
			if (trationLineData[i].trainstation.id == trainstation.id) {
				trationLineData[i].x = x - 15;
				trationLineData[i].y = 40;
				trationLineData[i].width = 30;
				break;
			}
		}
	}
	return x;
}
// 在画布上绘制信号机信息
function drawTeleseme(index, gap, teleseme, canvas) {
	var name = teleseme.name;
	var offSet = teleseme.offSet / 1000;
	var liCheng = teleseme.liCheng;
	var x = index + gap + offSet;
	var isLable = true;
	if (teleseme.type == 5) {
		isLable = false;
	}

	var trainStation = dataTDrawCanvas.getDrawing('teleseme', {
		name : name,
		x : x,
		offSet : offSet,
		liCheng : liCheng,
		isLable : isLable
	});
	trainStation.draw();

	for (var i = 0; i < trationLineData.length; i++) {
		if (trationLineData[i].type == 2) {
			if (trationLineData[i].teleseme.name == teleseme.name) {
				trationLineData[i].x = x - 15;
				trationLineData[i].y = 60;
				trationLineData[i].width = 30;
				break;
			}
		}
	}

	return x;
}
// 清空所有的基本用例矩形边框的颜色
function drawThumbnails(canvas, sequenceInfo, caseSelectIndex,reDrawBool) {
	//当前div滚动的距离
	var divScrollLength = 0;
	var context = canvas.getContext('2d');
	context.clearRect(0, 0, canvas.width, canvas.height);// 清空缩略图
	var currentX = 5;
	var totalWidth0 = 0;
	for (var i = 0; i < sequenceInfo.length; i++) {
		if (sequenceInfo[i].name.length <= 6) {
			sequenceInfo[i].width = caseWidth+30;
		} else {
			sequenceInfo[i].width = getStrLength(sequenceInfo[i].name) * 12+30;
		}
		totalWidth0 = totalWidth0 + sequenceInfo[i].width + 10;
	}
	if ((totalWidth0 + 100) <= 795) {
		sltCanvas.width = 795;
	} else {
		sltCanvas.width = totalWidth0 + 100;
	}

	var totalWidth = 0;
	for (var i = 0; i < sequenceInfo.length; i++) {
		var color = "rgb(128,138,135)";// 每次点击时，所有的基本用例框都是灰色
		// 定义缩略图位置信息
		sequenceInfo[i].x = currentX;
		sequenceInfo[i].y = 3;
		if (sequenceInfo[i].name.length <= 6) {
			sequenceInfo[i].width = caseWidth+30;
		} else {
			sequenceInfo[i].width = getStrLength(sequenceInfo[i].name)*12+30;
		}
		totalWidth = totalWidth + sequenceInfo[i].width;

		sequenceInfo[i].height = caseHeight;
		sequenceInfo[i].sort = (i + 1) + "";
		currentX += sequenceInfo[i].width + 10;
		var thumbnails;
		if (caseSelectIndex == sequenceInfo[i].sort) {
			thumbnails = sltTDrawCanvas.getDrawing('thumbnails', {
				baseCase : sequenceInfo[i],
				filled : true,
				selected:false
			});
			if(sequenceInfo[i-1] && (sequenceInfo[i].x+sequenceInfo[i].width)>$("#Thumbnails").width()){
				divScrollLength = sequenceInfo[i].x+sequenceInfo[i].width+30;
			}
		} else {
			thumbnails = sltTDrawCanvas.getDrawing('thumbnails', {
				baseCase : sequenceInfo[i],
				color : color
			});
		}
		// 绘制序列缩略图内的所有基本用例
		thumbnails.draw();
	}
	if(reDrawBool){
		//自动滚动到当前选中基本用例
		$("#Thumbnails").scrollLeft(divScrollLength);
	}
}

// 进入测试序列界面后展示测试序列内的基本用例并绘制
function showTestSequence(id) {
	$
			.ajax({
				url : '../../../sequence/querySequenceContentById',
				type : 'POST',
				data : {
					sequenceId : id
				// 测试序列的id
				},
				success : function(data) {
					if (data.flag == 0) {
						sequenceData = data.content;// 拿到序列的信息数据
						if (data.content.sequenceContent == null) {
							sequenceInfo = [];
						} else {
							sequenceInfo = eval(data.content.sequenceContent);// 点击的序列内的基本用例
							for(var i = 0;i<sequenceInfo.length;i++){
								sequenceInfo[i].caseElement = eval(sequenceInfo[i].caseContent);
							}
						}
						yxzzId = data.content.yxjlVersion;
						if (sequenceInfo.length !== 0) {// 只有测试序列内有基本用例时，才会绘制基本用例
							caseElements = sequenceInfo[0].caseElement;// 默认绘制第一个基本用例
							//重置所有元素为不选中状态
							resetSelected();
							if(caseElements.length>0){
								caseElements[0].x = initLocation.x;
								caseElements[0].y = initLocation.y;
								context.clearRect(0, 0, baseCaseCanvas.width,
										baseCaseCanvas.height);
								for (var i = 0; i < caseElements.length; i++) {
									setDrawSize(caseElements[i]);
								}
								resetCanvasHeight();
								// 初始化数据获取完成后，开始绘制图形
								drawProcessChart(caseElements);
								drawThumbnails(sltCanvas, sequenceInfo,
										caseSelectIndex,true);
							}
						}

						if (!firstGetCanvaseWidth && caseElements.length > 0) {

							canvasWidth = caseElements[caseElements.length - 1].x
									+ caseElements[caseElements.length - 1].width
									+ 100;
							if (canvasWidth < 1470) {
								canvasWidth = 1470;
							}
							// $("#canvasId").width(canvasWidth);
							baseTDrawCanvas.height = 750;
							baseTDrawCanvas.width = canvasWidth;
							$('#parameterBottom')
									.css('width', canvasWidth - 95);
							if(caseElements.length>0){
								caseElements[0].x = initLocation.x;
								caseElements[0].y = initLocation.y;
								//设置当前默认第一个控件为选中状态
								selectTargetId = caseElements[0].id;
								setSelectedById(selectTargetId);
								context.clearRect(0, 0, baseCaseCanvas.width,
										baseCaseCanvas.height);
								for (var i = 0; i < caseElements.length; i++) {
									setDrawSize(caseElements[i]);
								}
								resetCanvasHeight();
								// 初始化数据获取完成后，开始绘制图形
								drawProcessChart(caseElements);
								canvasClick();
							}
							firstGetCanvaseWidth = true;
						}
					} else {
						danger(data.errorInfo);
					}
				}
			});
}
// 上方缩略图内基本用例点击变色效果
function canvasClicks(e) {
	//重置所有元素为不选中状态
	resetSelected();
	// 每次点击都会清空数据展示区域
	resetMsg();
	var ps = getEventPosition(e);// 当前点击位置的坐标
	if (sequenceInfo.length > 0) {// 当前用例内有基本用例时的操作
		for (var i = 0; i < sequenceInfo.length; i++) {
			if (sequenceInfo[i].caseElement) {
				if (ps.x > sequenceInfo[i].x
						&& ps.x < sequenceInfo[i].x + sequenceInfo[i].width
						&& ps.y > (sequenceInfo[i].y - 15)
						&& ps.y < (sequenceInfo[i].y + sequenceInfo[i].height+15)) {
					caseSelectIndex = sequenceInfo[i].sort + "";// 当前选中用例下标
					copyCaseSelectIndex = sequenceInfo[i].sort + "";
					sltCanvasSelectObj = [];
					sltCanvasSelectObj = [].concat(JSON.parse(JSON
							.stringify(sequenceInfo)));
					drawThumbnails(sltCanvas, sequenceInfo, caseSelectIndex,false);// 重绘缩略图区域
					caseElements = sequenceInfo[i].caseElement;
					if(caseElements.length>0){
						caseElements[0].x = initLocation.x;
						caseElements[0].y = initLocation.y;
						//设置当前默认第一个控件为选中状态
						selectTargetId = caseElements[0].id;
						setSelectedById(selectTargetId);
						context.clearRect(0, 0, baseCaseCanvas.width,
								baseCaseCanvas.height);
						for (var i = 0; i < caseElements.length; i++) {
							setDrawSize(caseElements[i]);
						}
						resetCanvasHeight();
						// 初始化数据获取完成后，开始绘制图形
						drawProcessChart(caseElements);
						canvasClick();
					}
					return false;
				}
			}
		}
	}
}

function testSequence() {// 测试序列树信息获取
	// 树形图setting配置
	setting = {
		view : {
			showLine : true,// 是否显示节点之间的连线
			fontCss : {
				'color' : 'black',
				'font-weight' : 'bold'
			}
		// 字体样式函数
		},
		data : {
			simpleData : {// 简单数据模式
				enable : true,
				idKey : "id",
				pIdKey : "pId",
				rootPId : ""
			}
		},
		callback : {
			onDblClick : function(event, treeId, treeNode) {
				clcikAddSequeceBool = false;
				// 每次双击打开一个序列时，先清空缩略图和画布
				if (!treeNode.isParent) {// 点击序列时更新右侧数据
					// if($("#save").attr("hidden")==undefined){//如果有权限时，可以展示测试序列
					var id = treeNode.id;// 获取到点击的序列的id
					caseSelectIndex = "1";// 设置第一个选中
					$
							.ajax({
								url : '../../../sequence/querySequenceContentById',
								type : 'POST',
								data : {
									sequenceId : id
								// 测试序列的id
								},
								success : function(data) {
									console.log(data);
									var currentSquenceSelected = [].concat(JSON.parse(JSON.stringify(sequenceInfo))).length;
									if (data.flag == 0) {
										if (data.content.length <= 0) {
											var info = "<div style='color:black;'>此序列为空！</div>";
											warning(info);
										}
										if ($("#save").attr("hidden") == undefined) {// 如果有权限时，可以展示测试序列
											var squenceList = eval(data.content.sequenceContent);
											for (var i = 0; i < squenceList.length; i++) {
												squenceList[i].caseElement = eval(squenceList[i].caseContent);
												sequenceInfo.push(squenceList[i]);// 点击的序列内的基本用例
											}
										} else {
											var squenceList = eval(data.content.sequenceContent);
											for (var i = 0; i < squenceList.length; i++) {
												squenceList[i].caseElement = eval(squenceList[i].caseContent);
												
											}
											sequenceInfo = squenceList;// 点击的序列内的基本用例
										}

										if (sequenceInfo.length !== 0) {// 只有测试序列内有基本用例时，才会绘制基本用例
											caseElements = sequenceInfo[currentSquenceSelected].caseElement;// 默认绘制第一个基本用例
											if(caseElements.length>0){
												caseElements[0].x = initLocation.x;
												caseElements[0].y = initLocation.y;
												//设置当前默认第一个控件为选中状态
												selectTargetId = caseElements[0].id;
												setSelectedById(selectTargetId);
												context.clearRect(0, 0, baseCaseCanvas.width,
														baseCaseCanvas.height);
												for (var i = 0; i < caseElements.length; i++) {
													setDrawSize(caseElements[i]);
												}
												resetCanvasHeight();
												// 初始化数据获取完成后，开始绘制图形
												drawProcessChart(caseElements);
												canvasClick();
												caseSelectIndex = (currentSquenceSelected+1) + "";
												drawThumbnails(sltCanvas, sequenceInfo,
														caseSelectIndex,true);
											}
										}
									} else {
										danger(data.errorInfo);
									}
								}
							});
				}

			}
		}
	};
	onLoadZTree();
}
// 删除序列中的基本用例信息
function deleteBaseCase() {
	for (var i = 0; i < sequenceInfo.length; i++) {// 遍历缩略图内基本用例
		if (sequenceInfo[i].sort == caseSelectIndex) {
			sequenceInfo.splice(i, 1);// 删除点击的基本用例
			caseSelectIndex = "1";
			drawThumbnails(sltCanvas, sequenceInfo, caseSelectIndex,true);// 重绘缩略图区域
			if (sequenceInfo.length > 0) {
				caseElements = sequenceInfo[0].caseElement;
			} else {
				caseElements = [];
			}
			context.clearRect(0, 0, baseCaseCanvas.width, baseCaseCanvas.height);
			for (var i = 0; i < caseElements.length; i++) {
				setDrawSize(caseElements[i]);
			}
			resetCanvasHeight();
			drawProcessChart(caseElements);
			
			resetMsg();
		}
	}
	console.log(sequenceInfo);
}
// 在canvas内绘制caseElements元素 value是回显的文本
function draw(canvas, elementTypes, caseElements) {
	// 清空画布内的内容
	var context = canvas.getContext('2d');
	context.clearRect(0, 0, canvas.width, canvas.height);
	// 绘制坐标轴和直线
	// drawDashLine(canvas, elementTypes);
	var coordinate = baseTDrawCanvas.getDrawing('coordinate', {
		elementTypes : elementTypes,
		hPoint : {
			x1 : 35,
			y1 : 660,
			x2 : canvas.width,
			y2 : 660
		},
		vPoint : {
			x1 : 95,
			y1 : 50,
			x2 : 95,
			y2 : 750
		},
		dashPoint : {
			x1 : 10,
			y1 : (150),
			x2 : canvas.width,
			y2 : (150)
		},
		dashSpace : 40,
		color : '#817471'
	});
	coordinate.draw();
	stroke = '#6c615f';
	// 重新绘制条件轴图形
	if (caseElements) {
		for (var i = 0; i < caseElements.length; i++) {
			if (caseElements[i].type == "011") {
				for (var j = 0; j < caseElements[i].children.length; j++) {
					if (caseElements[i].children[j].data.length >= 1) {// 如果有外部参数，高亮显示
						for (var k = 0; k < caseElements[i].children[j].data.length; k++) {
							if (caseElements[i].children[j].data[k].required == "1") {
								caseElements[i].children[j].state = 1;
								continue;
							}
						}
					}
				}

				var isShow = false;
				// 根据后台的数据判断是否有信号机
				for (var p = 0; p < caseElements[i].data.length; p++) {
					if (caseElements[i].data[p].name == "011001007") {
						if (caseElements[i].data[p].value
								&& caseElements[i].data[p].value != ""
								&& caseElements[i].data[p].value != null
								&& caseElements[i].data[p].value != "-1") {
							isShow = true;
							caseElements[i].signalBool = true;
							caseElements[i].signalName = caseElements[i].data[p].value;
						}
					}
				}
				// 根据前台的输入框判断是否有信号机
				if (caseElements[i].signalBool && caseElements[i].signalBool) {
					isShow = true;
				}

				var conditionArea = baseTDrawCanvas.getDrawing('conditionArea',
						{
							obj : caseElements[i],
							elementTypes : elementTypes,
							conditionState : caseElements[i].conditionState,
							signalObj : {
								x : caseElements[i].x + caseElements[i].width
										- 40,
								isShow : isShow
							}
						});// 条件轴的状态
				conditionArea.draw();
			} else if (caseElements[i].type == "012") {
				// drawSignal(canvas,caseElements[i]);
				var signal = baseTDrawCanvas.getDrawing('signal', {
					obj : caseElements[i],
					color : '#D6D6D4'
				});
				signal.draw();
			} else if (caseElements[i].type == "013") {
				// drawGraph(canvas);
				var graph = baseTDrawCanvas.getDrawing('graph');
				graph.draw();
			} else if (caseElements[i].type == "014") {
				// drawKvalueMap(canvas,caseElements[i]);
				var kvalueMap = baseTDrawCanvas.getDrawing('kvalueMap', {
					obj : caseElements[i]
				});
				kvalueMap.draw();
			}
		}
	}
}
// 加载测试序列zTree树形图
function onLoadZTree() {
	var treeNodes;
	$.ajax({
		async : false,// 是否异步
		cache : false,// 是否使用缓存
		data : {},// 测试序列编辑页面树
		type : 'POST',// 请求方式：post
		dataType : 'json',// 数据传输格式：json
		url : "../../../sequence/querySequenceTree",// 请求路径
		success : function(data) {
			if (data.flag == 0) {
				// 请求成功后处理函数
				treeNodes = data.content;// 把后台封装好的简单Json格式赋给treeNodes
				var zTree = $("#tree");
				zTree = $.fn.zTree.init(zTree, setting, treeNodes);
			} else {
				danger(data.errorInfo);
			}
		}
	});
}

function canvasClick() {
	var id = "";
	if(selectTargetData == null){
		return;
	}
	// 根据当前点击点的坐标获取点击的元素并设置选中
	var selection = [ selectTargetData ];
	for (var i = 0; i < selection.length; i++) {
		id = selection[i].id;// 点击的元素的id
	}
	if (selection.length > 0) {
		$("#caseNamee").empty();
		$("#elementContents").empty();
		$('#conDescription').empty(); // 清空控件说明描述内容
		$('#outParameter').empty();// 清空外部参数内容
		var selectElement = "";
		selectElement = selection[0];
		$('#controlDescription').css('display', 'block');
		$('#shuxingContent').css('display', 'block');
		$('#controlDescription').css('display', 'block');
		var description = selectElement.description;// 控件描述内容获取
		$("#caseNamee").append(
				"<div id='elementName'><span class='backblock' id=" + id
						+ ">" + selectElement.name + "-基本属性</span></div>");// 元素名称内容插入
		$("#conDescription").append(
				"<div id='controlDescription2'>" + description + "</div>");// 描述内容插入到标签
		showAttribute(selectElement, caseElements);
	}
	rightParameter();// 根据用户权限判断让右侧的参数修改和不可修改
}

//显示右侧属性信息
function showAttribute(selectElement, caseElements) {
	var shuXing = selectElement.attributes;// 拿到所有的data数据
	$('#externalParameter').css('display', 'none');// 默认外部参数的div为隐藏状态
	$('#controlDescription').css('display', 'block');
	$('#shuxingContent').css('display', 'block');
	if (shuXing.length > 0) {
		var trainType = "";// 列车类型
		var trainBZ = "";// 标识
		for (var j = 0; j < shuXing.length; j++) {
			// 通过data的type属性判断input的类型
			// input是文本输入框且data数据中的ranger不是null时，获取限定值
			var shuxing = shuXing[j];
			var value1 = shuxing.value;
			var name = shuxing.name;
			var displayValue = shuxing.displayValue;
			if (value1 == null) {
				value1 = shuxing.defultValue;
			}
			if (shuxing.type == "1") {
				// 拿到输入数字的限定值
				var range = shuxing.range;
				var rangValue = "";
				var div = "";
				if (range != null) {
					var nums = range.split(',');
					var minnum = parseInt(nums[0]);
					var maxnum = parseInt(nums[1]);
					rangValue = "min='" + minnum + "' max='" + maxnum + "'";
				}
				if (shuxing.unit) {
					div = ("<div class='defaultProperty'>"
							+ "<span>"
							+ shuxing.name
							+ "</span>"
							+ "<input type='number' id='"
							+ shuxing.id
							+ "' name='"
							+ name
							+ "' code='" + shuxing.code
							+ "' value='"
							+ value1
							+ "'"
							+ rangValue
							+ " onInput='set_a_value(this)'><span style='width:40px;margin-left:5px'>"
							+ shuxing.unit + "</span></div>");
				} else {
					div = ("<div class='defaultProperty'>" + "<span>"
							+ shuxing.name + "</span>"
							+ "<input type='number' id='" + shuxing.id
							+ "' code='" + shuxing.code
							+ "' name='" + name + "' value='" + value1 + "'"
							+ rangValue + " onInput='set_a_value(this)'>" + "</div>");
				}
				shuxing.displayValue = value1;
				if (shuxing.required == "0") {
					$('#shuxingContent').css('display', 'block');
					$("#elementContents").append(div);
				} else {
					$('#externalParameter').css('display', 'block');// 当有外部参数时，外部参数div才显示
					$("#outParameter").append(div);
				}

			} else if (shuxing.type == "2") {// 文本输入框
				if (value1 == "null") {
					value1 = "-1";
				}
				var div = "";
				if (shuxing.unit) {
					div = ("<div class='defaultProperty'>"
							+ "<span>"
							+ shuxing.name
							+ "</span>"
							+ "<input  type='text' id='"
							+ shuxing.id
							+ "' name='"
							+ name
							+ "' code='" + shuxing.code
							+ "' value='"
							+ value1
							+ "'"
							+ " onInput='set_a_value(this)'><span style='width:40px;margin-left:5px'>"
							+ shuxing.unit + "</span></div>");
				} else {
					div = ("<div class='defaultProperty'>" + "<span>"
							+ shuxing.name + "</span>" + "<input  type='text' id='"
							+ shuxing.id + "' name='" + name+ "' code='" + shuxing.code + "' value='"
							+ value1 + "'" + " onInput='set_a_value(this)'>" + "</div>");
				}
				shuxing.displayValue = value1;
				if (shuxing.required == "0") {
					$('#shuxingContent').css('display', 'block');
					$("#elementContents").append(div);
				} else {
					$('#externalParameter').css('display', 'block');// 当有外部参数时，外部参数div才显示
					$("#outParameter").append(div);
				}
			}else if (shuxing.type == "3") {// 下拉框单选
				var div = "";
				div = ("<div class='defaultProperty'>" + "<span>"
						+ shuxing.name + "</span>" + "<select id='"
						+ shuxing.id + "' value= '" + value1
						+ "' name='" + shuxing.code
						+ "' code='" + shuxing.code
						+ "' onchange='set_a_value(this)'>"
						+ "</select>" + "</div>");

				if (shuxing.required == "0") {
					$('#shuxingContent').css('display', 'block');
					$("#elementContents").append(div);
				} else {
					$('#externalParameter').css('display', 'block');// 当有外部参数时，外部参数div才显示
					$("#outParameter").append(div);
				}
				if (displayValue != null && value1 != "null") {
					if (name == "007004010" || name == "007004011"
							|| name == "007004013" || name == "007004014"
							|| name == "007004015") {
						$("#" + shuxing.id).append(
								"<option id=" + value1
										+ " selected='selected' >"
										+ displayValue + "</option>");
					}
				}
				var dic = getSelectListByCode(shuxing.dict);
				var copyDic = [].concat(JSON.parse(JSON.stringify(dic)));
				if(shuxing.dict =='051'){
					if(shuxing.self_conditionType!=null){
						if(shuxing.self_conditionType == 0){
							copyDic= getSelectListByCode(shuxing.dict);
							shuxing.dicMu  = [copyDic[0]];
						}else{
							copyDic.shift();
							shuxing.dicMu = copyDic;
						}
					}else{
						shuxing.dicMu = copyDic;
					}
				}else{
					shuxing.dicMu = copyDic;
				}
				//当下拉框默认值为“请选择”时，value=“请选择”，此时相当于值为空
				if(value1 == "请选择"){
					$("#" + shuxing.id).append(
							"<option id='-1' value= '请选择'>" + "请选择"
							+ "</option>");
				}
				if (shuxing.dict != null) {
					for (var i = 0; i < shuxing.dicMu.length; i++) {
						var dicId = shuxing.dicMu[i].id;
						var dicName = shuxing.dicMu[i].name;
						if (value1 == dicId) {
							$("#" + shuxing.id).append(
									"<option id='" + dicId + "'value='"
											+ dicId
											+ "' selected='selected' >"
											+ dicName + "</option>");
							shuxing.displayValue = dicName;
						} else {
							$("#" + shuxing.id).append(
									"<option id='" + dicId + "' value= '"
											+ dicId + "'>" + dicName
											+ "</option>");
						}
					}
				}
				//LKJ换装控件中软件类型和文件名称的切换联动
				if(shuxing.code == "007016002"){
					storeVersionByType = [];
					getLKJByType($("select[name='007016002']").val());
				}
			}else if (shuxing.type == "4") {// 下拉框多选
				var div = "";
				var dicMu = [];
				var selectedIdArray = [];
				if(value1!=""){
					selectedIdArray = value1.split(',');
				}
				if (shuxing.atrributeId == "78") {// 如果属性的ID是78
					$(".conditionsTemplate").remove();// 删除条件组合
					$(".headInformation").remove();// 删除头部信息
					generateConditions(shuxing);// 生成条件组合功能的函数
				} else {
					div = ("<div class='defaultProperty'>" + "<span>"
							+ shuxing.name + "</span>" + "<select class='multipleSelect' multiple='multiple' id='"
							+ shuxing.id + "' value= '" + value1
							+ "' name='" + name
							+ "' code='" + shuxing.code
							+ "' onchange='set_a_value(this)'>"
							+ "</select>" + "</div>");

					if (shuxing.required == "0") {
						$('#shuxingContent').css('display', 'block');
						$("#elementContents").append(div);
					} else {
						$('#externalParameter').css('display', 'block');// 当有外部参数时，外部参数div才显示
						$("#outParameter").append(div);
					}
					dicMu= getSelectListByCode(shuxing.dict);
					shuxing.dicMu = dicMu;
					if (shuxing.dict != null) {
						for (var i = 0; i < dicMu.length; i++) {
							var dicId = dicMu[i].id;
							var dicName = dicMu[i].name;
							var bool = false;
							for(var k = 0;k<selectedIdArray.length;k++){
								if(selectedIdArray[k] == dicId){
									bool = true;
									break;
								}
							}
							if (bool) {
								$("#" + shuxing.id).append(
										"<option id='" + dicId + "'value='"
												+ dicName
												+ "' selected='selected' >"
												+ dicName + "</option>");
							} else {
								$("#" + shuxing.id).append(
										"<option id='" + dicId + "' value= '"
												+ dicName + "'>" + dicName
												+ "</option>");
							}
						}
					} 
				}
				$('.multipleSelect').multiselect( { enableClickableOptGroups: true,
			         enableCollapsibleOptGroups: true,
			         includeSelectAllOption: true
				});
			} else if (shuxing.type == "5") {
				div = ("<div class='defaultProperty'>"
						+ "<span style='display:inline;vertical-align:middle'>"
						+ shuxing.name
						+ "</span>"
						+ "<a class='input-group date' id='datetimepicker1' style='display:inline-block;vertical-align:middle'>"
						+ "<input type='text'  class='form-control'  id='"
						+ shuxing.id
						+ "' onChange='set_Time_value(this)' style='width: 160px; height: 30px;background-color:#161b2f;border:1px solid #53597B;color:#ffffff' />"
						+ "<span class='input-group-addon' style='float: left; width: 50px; height: 30px;background-color:#337ab7;border:1px solid #53597B'>"
						+ "<span id='datetimepicker2'  class='glyphicon glyphicon-calendar' style='width:25px;margin-left:0px;color:#e0ecff'></span></span></a>" + "</div>");
				if (shuxing.required == "0") {
					$('#shuxingContent').css('display', 'block');
					$("#elementContents").append(div);
				} else {
					$('#externalParameter').css('display', 'block');// 当有外部参数时，外部参数div才显示
					$("#outParameter").append(div);
				}
				Datetime(shuxing, shuxing.id);
			}  else if (shuxing.type == "6") {// 始发站
				var dic = getSelectListByCode(shuxing.dict);
				var div = "";
				var code = shuxing.code;
				if (code == "007004004") {
					// 初始化列车类型下拉框值和车种标识下拉值
					getLKJTrainTypeSequence("0101120180502134514001852",value1,shuxing);
				}
				if (code == "007004010") {// 起始站名 输入下拉
					div = "<div class='defaultProperty'>"
							+ "<span>"
							+ shuxing.name
							+ "</span>"
							+ "<input type='text' style='width:25px' name='"+code+"'  onchange='startStationPYChange(this)' onkeyup='validate(this,1)'>"
							+ "<select id='"
							+ shuxing.id
							+ "' value= '"
							+ value1
							+ "' name='"
							+ code
							+ "' code='" + shuxing.code
							+ "' onchange='startStationChange(this)'></select></div>";
				} else if (shuxing.code == "007004013") {// 发车方向下拉选项
					div = ("<div class='defaultProperty'>" + "<span>"
							+ shuxing.name + "</span>" + "<select id='"
							+ shuxing.id + "' value= '" + value1
							+ "' name='" + code
							+ "' code='" + shuxing.code
							+ "' onchange='directionChange(this)'>"
							+ "</select>" + "</div>");
				} else if (shuxing.code == "007004014" || shuxing.code =='001002001' || shuxing.code == '001003001') {// 终止站,车站名称
					var type = 0;
					if(shuxing.code == "007004014"){
						type = 0;
					}else if(shuxing.code == "001002001"){
						type = 1;
					}else if(shuxing.code == "001003001"){
						type = 2;
					}
					div = "<div class='defaultProperty'>"
							+ "<span>"
							+ shuxing.name
							+ "</span>"
							+ "<input type='text' style='width:25px' onchange='stopStationPYChangeSquence(this,"+type+")' onkeyup='validate(this,1)'>"
							+ "<select id='" + shuxing.id + "' value= '"
							+ value1 + "' name='" + code
							+ "' code='" + shuxing.code
							+ "' onchange='set_a_value(this)'"
							+ "' ></select></div>";
				}else if(shuxing.code == "007016001"){//LKJ换装控件中软件类型和文件名称的切换联动
					console.log(storeVersionByType);
					shuxing.dicMu = storeVersionByType;
					div = ("<div class='defaultProperty'>" + "<span>"
							+ shuxing.name + "</span>" + "<select id='"
							+ shuxing.id + "' value= '" + value1
							+ "' name='" + shuxing.code
							+ "' code='" + shuxing.code
							+ "' onchange='set_a_value(this)'>"
							+ "</select>" + "</div>");
				} else {
					div = ("<div class='defaultProperty'>" + "<span>"
							+ shuxing.name + "</span>" + "<select id='"
							+ shuxing.id + "' value= '" + value1
							+ "' name='" + code
							+ "' code='" + shuxing.code
							+ "' onchange='set_a_value(this)'>"
							+ "</select>" + "</div>");
				}

				if (shuxing.required == "0") {
					$('#shuxingContent').css('display','block');
					$("#elementContents").append(div);
				} else {
					$('#externalParameter').css('display','block');//当有外部参数时，外部参数div才显示
					$("#outParameter").append(div);
				}
				
				dicMu= getSelectListByCode(shuxing.dict);
				shuxing.dicMu = dicMu;
				//当从字典接口中后对接下拉菜单数据时，直接显示菜单数据，如果没有那么默认下拉菜单只有value一项，并选中
				if (shuxing.dict != null && dicMu!=null&& dicMu.length>0) {
					for (var i = 0; i < dicMu.length; i++) {
						var dicId = dicMu[i].id;
						var dicName = dicMu[i].name;
						if (value1 == dicId) {
							$("#" + shuxing.id).append(
									"<option id='" + dicId + "'value='"
											+ dicId
											+ "' selected='selected' >"
											+ dicName + "</option>");
						} else {
							$("#" + shuxing.id).append(
									"<option id='" + dicId + "' value= '"
											+ dicId + "'>" + dicName
											+ "</option>");
						}
					}
				}else{
					$("#" + shuxing.id).append(
							"<option id='" + shuxing.value + "'value='"
									+ value1
									+ "' selected='selected' >"
									+ shuxing.displayValue + "</option>");
				}
				
				//lkj控件中文件名称和软件类型联动特殊处理
				if(code=="007016001"){
					$("#" + shuxing.id).find("option").remove();
					shuxing.dicMu = storeVersionByType;
					for(var i = 0;i<storeVersionByType.length;i++){
						if (value1 == storeVersionByType[i].VERSION_ID) {
							$("#" + shuxing.id).append(
									"<option id='" + storeVersionByType[i].VERSION_ID + "'value='"
									+ storeVersionByType[i].VERSION_ID
									+ "' selected='selected' >"
									+ storeVersionByType[i].VERSION_NAME + "</option>");
						} else {
							$("#" + shuxing.id).append(
									"<option id='" + storeVersionByType[i].VERSION_ID + "' value= '"
									+ storeVersionByType[i].VERSION_ID + "'>" + storeVersionByType[i].VERSION_NAME
									+ "</option>");
						}
					}
				}
			}
		}
	}
}

function set_a_value(th) {// th this用来获取属性值，ys就是整个元素对象
	if (th.max) {
		if (th.value == '') {
			var info = "<div style='color:black;'>输入值不能为空！</div>";
			if (th.defaultValue) {
				th.value = th.defaultValue;
			} else if (th.min) {
				th.value = th.min;
			} else {
				th.value = 0;
			}
			warning(info);
			return;
		}
		// 当输入框的输入内容不在有效范围内，则提示重新输入
		if (Number(th.value) > Number(th.max)
				|| Number(th.value) < Number(th.min)) {
			var info = "<div style='color:black;'>请输入有效范围的数字:" + th.min + "-"
					+ th.max + "</div>";
			if (th.defaultValue) {
				th.value = th.defaultValue;
			} else {
				th.value = 0;
			}
			warning(info);
			return false;
		}
	}
	
	//当外部参数的输入框不能为空
	if(th.attributes.type && (th.attributes.type.nodeType == "1" || th.attributes.type.nodeType == "2")){
		if (th.value == ''){
			var info = "<div style='color:black;'>输入值不能为空！</div>";
			if (th.defaultValue) {
				th.value = th.defaultValue;
			} else if (th.min) {
				th.value = th.min;
			} else {
				th.value = 0;
			}
			warning(info);
			return;
		}
	}
	if(th.attributes.code){
		//列车类型和车种标识之间的切换联动
		if(th.attributes.code.nodeValue == "007004004"){
			var value = $("select[name='007004004']").val();
			var children = getTrainTypeChildren("无",lclxArray);
			$("select[name='007004003']")[0].options.length=0;//清空下拉内容，重新赋值
			var dicArray = [];
			$("select[name='007004003']")[0].options.add(new Option("请选择", "请选择"));
			for(var k=0;k<children.length;k++){
				$("select[name='007004003']")[0].options.add(new Option(children[k].name, children[k].id));
				dicArray.push({name:children[k].name,id:children[k].id});
			}
			for(var i = 0;i<selectTargetData.attributes.length;i++){
				if(selectTargetData.attributes[i].code == "007004003"){
					selectTargetData.attributes[i].dicMu = dicArray;
				}
			}
			//切换车种标识时，列车类型数据清空
			var currentAttributes = selectTargetData.attributes;
			for(var i = 0;i<currentAttributes.length;i++){
				if(currentAttributes[i].code == "007004003"){
					currentAttributes[i].value = "";
					currentAttributes[i].displayValue = "请选择";
				}
			}
			//LKJ换装控件中软件类型和列车标志的切换联动
		}else if(th.attributes.code.nodeValue == "007004003"){
			var value = $("select[name='007004003']").val();
			//切换列车类型时，也把列车标志切换到对应选项
			if(th.value != "请选择"){
				var lzlxId = getLzbzByTranType(value);
				$("select[code='007004016']").find("option[id='"+lzlxId+"']").prop("selected","selected");
			}else{
				$("select[code='007004016']").find("option[id='-1']").prop("selected","selected");
			}
		}else if(th.name == "007016002"){
			//获取联动的文件名称的数据
			getLKJByType($("select[name='007016002']").val());
		}
	}
	
	saves(th);
	console.log(caseElements);
	//当切换下拉框时，绘图显示变动
	//按键输入、平调信号、色灯信号
	if(th.attributes.code){
		if(th.attributes.code.nodeValue == "007001003"
			||th.attributes.code.nodeValue == "004004001"
				||th.attributes.code.nodeValue == "004002002"){
			getParentDataByChild(th.attributes.id.nodeValue,th.selectedOptions[0].innerText);
		}
		//当改变时间时时，绘图显示变动
		if(th.attributes.code.nodeValue == "010001001"){//时间输入
			getParentDataByChild(th.attributes.id.nodeValue,"延时"+th.value+"s");
		}
	}
	//切换条件控件中的数据项
	if(th.attributes.code && th.attributes.code.nodeValue && th.attributes.code.nodeValue == "009001003"){
		var selectObjData = null;
		for(var i = 0;i<shuJuAllDataArray.length;i++){
			if(shuJuAllDataArray[i].code == th.selectedOptions[0].id){
				selectObjData = shuJuAllDataArray[i];
				break;
			}
		}
		setConditionElementType(th.attributes.id.nodeValue,selectObjData);
		canvasClick();
	}
}
function setConditionElementType(id,selectObjData){
	for(var i = 0;i<caseElements.length;i++){
		setConditionElementTypeLoop(caseElements[i],id,selectObjData);
	}
}
function setConditionElementTypeLoop(obj,id,selectObjData){
	if(obj.type =='015'){
		var bool = false;
		for(var i = 0;i<obj.conditionList.length;i++){
			for(var j = 0;j<obj.conditionList[i].attributes.length;j++){
				if(obj.conditionList[i].attributes[j].id == id){
					bool = true;
				}
				if(bool){
					if(selectObjData){
						obj.conditionList[i].attributes[4].type = (parseInt(selectObjData.type)+1) +"";
						obj.conditionList[i].attributes[4].dict = selectObjData.dictCode;
					}else{
						obj.conditionList[i].attributes[4].type = "1";
						obj.conditionList[i].attributes[4].dict = null;
					}
					
					return;
				}
			}
		}
		if(bool == false){
			for(var i = 0;i<obj.leftChildrens.length;i++){
				setConditionElementTypeLoop(obj.leftChildrens[i],id,selectObjData);
			}
			for(var i = 0;i<obj.rightChildrens.length;i++){
				setConditionElementTypeLoop(obj.rightChildrens[i],id,selectObjData);
			}
		}
	}else if(obj.type =='016'){
		var bool = false;
		for(var i = 0;i<obj.conditionList.length;i++){
			for(var j = 0;j<obj.conditionList[i].attributes.length;j++){
				if(obj.conditionList[i].attributes[j].id == id){
					bool = true;
				}
				if(bool){
					if(selectObjData){
						obj.conditionList[i].attributes[4].type = (parseInt(selectObjData.type)+1) +"";
						obj.conditionList[i].attributes[4].dict = selectObjData.dictCode;
					}else{
						obj.conditionList[i].attributes[4].type = "1";
						obj.conditionList[i].attributes[4].dict = null;
					}
					
					return;
				}
			}
		}
		if(bool == false){
			for(var i = 0;i<obj.childrens.length;i++){
				setConditionElementTypeLoop(obj.childrens[i],id,selectObjData);
			}
		}
	}
}
function transferSave(th) {// 右侧属性值一修改就保存
	saves(null);
	var atrrCode = th.name;
	if (atrrCode == "011001007") {// 信号机编号
		var isShow = false;
		var valss = th.value;
		if (valss != "") {
			isShow = true;
		}
		for (var i = 0; i < caseElements.length; i++) {
			var children = caseElements[i].data;
			for (var k = 0; k < children.length; k++) {
				if (th.id == children[k].id) {
					if (isShow) {
						if (!caseElements[i].signalBool) {
							caseElements[i].signalBool = true;
						}
					} else {
						if (caseElements[i].signalBool) {
							caseElements[i].signalBool = false;
						}
					}
					caseElements[i].signalName = valss;
					var context = baseCaseCanvas.getContext('2d');
					context.clearRect(0, 0, canvasWidth, baseCaseCanvas.height);
					draw(baseCaseCanvas, elementTypes, caseElements);
				}
			}
		}
	}
}
// 点击左侧按钮效果
function accordion() {
	$("#testSequence").click(function() {
		$("#testSequence").css({
			"background-color" : "#337AB7",
			"color" : "white"
		});
		$("#basiCase").css({
			"background-color" : "rgb(12,27,46)",
			"color" : "#b4b2b2"
		});
		$("#basecase").css("display", "none");
		$("#sequence").css("display", "block");
		$("html,body").animate({scrollTop:0},5);
		$("#canvasSeId").animate({scrollTop:0},5);
		$("#canvasDiv").animate({scrollTop:0},5);
		$("#contentCenter").animate({scrollTop:0},5);
	});
	$("#basiCase").click(function() {

		$("#basiCase").css({
			"background-color" : "#337AB7",
			"color" : "white"
		});
		$("#testSequence").css({
			"background-color" : "rgb(12,27,46)",
			"color" : "#b4b2b2"
		});
		$("#sequence").css("display", "none");
		$("#basecase").css("display", "block");
		$("html,body").animate({scrollTop:0},5);
		$("#canvasSeId").animate({scrollTop:0},5);
		$("#canvasDiv").animate({scrollTop:0},5);
		$("#contentCenter").animate({scrollTop:0},5);
	});
}
// 保存右侧属性区域修改后的信息
function saves(th) {
	// 拿到右侧所有属性所在的div
	var currentAttributes = selectTargetData.attributes;
	for (var i = 0; i < currentAttributes.length; i++) {
		var newValue = "";
		var displayValue = "";
		var dic = "";// 动态dic
		if (currentAttributes[i].type == "1"
				|| currentAttributes[i].type == "2") {
			if ($('#' + currentAttributes[i].id).val() == ""
					|| $('#' + currentAttributes[i].id).val() == "null") {
				newValue = "";
			} else {
				newValue = $('#' + currentAttributes[i].id).val();
				currentAttributes[i].displayValue = newValue;
				currentAttributes[i].value = newValue;
			}
		} else if (currentAttributes[i].type == "3") {
			var str = $('#' + currentAttributes[i].id).val();
			for(var j = 0;j<currentAttributes[i].dicMu.length;j++){
				if(str == currentAttributes[i].dicMu[j].id){
					newValue = currentAttributes[i].dicMu[j].name;
				}
			}
			displayValue = str;
			currentAttributes[i].value = str;
			currentAttributes[i].displayValue = newValue;
		}else if (currentAttributes[i].type == "4") {
        	var idListStr = "";
        	var nameListStr = "";
			var selectdOption = $("select.multipleSelect");
			if(selectdOption.length>0){
				for(var j=0;j<selectdOption[0].length;j++){
					if(selectdOption[0][j].selected){
						if(idListStr == ""){
							idListStr+=currentAttributes[i].dicMu[j].id;
							nameListStr+=currentAttributes[i].dicMu[j].name;
						}else{
							idListStr+=","+currentAttributes[i].dicMu[j].id;
							nameListStr+=","+currentAttributes[i].dicMu[j].name;
						}
					}
				}
			}
			newValue = idListStr;
			displayValue = nameListStr;
			currentAttributes[i].value = newValue;
			currentAttributes[i].displayValue = displayValue;
		}else if (currentAttributes[i].type == "5") {//时间控件
			var str = $('#' + currentAttributes[i].id).val();
			if(str!=-1){
				while(str.indexOf(" ")>=0){
					str = str.replace(' ',"");
				}
				while(str.indexOf("-")>=0){
					str = str.replace('-',"");
				}
				while(str.indexOf(":")>=0){
					str = str.replace(':',"");
				}
			}
			newValue = str;
		}else if(currentAttributes[i].type == "6"){
			if(th&& th.attributes &&th.attributes.code && th.selectedOptions && th.selectedOptions[0]){
				var attrName = currentAttributes[i].code;
				if(attrName==th.attributes.code.nodeValue){
					if ($('#' + currentAttributes[i].id)[0].selectedOptions.length == 0) {// 当没有数据时，为空
						displayValue = "";
						newValue='';
					} else {
						displayValue = $('#' + currentAttributes[i].id)[0].selectedOptions[0].text;
						newValue = th.selectedOptions[0].value;
					}
					currentAttributes[i].value = newValue;
					currentAttributes[i].displayValue = displayValue;
				}
				//lkj控件中文件名称和软件类型联动特殊处理
				if(attrName == "007016001"){
					var str = $('#' + currentAttributes[i].id).val();
					for(var j = 0;j<storeVersionByType.length;j++){
						if(str == storeVersionByType[j].VERSION_ID){
							newValue = storeVersionByType[j].VERSION_NAME;
						}
					}
					displayValue = str;
					currentAttributes[i].value = str;
					currentAttributes[i].displayValue = newValue;
				}
				//当车种标示为“无”时，发送空
				if(attrName == "007004004"){
					if(currentAttributes[i].value == "无"){
						currentAttributes[i].value = "";
						currentAttributes[i].displayValue = "";
					}
				}
			}
		}
	}
};
// 获取选中元素下标
function getSelectElements() {
	var selection = [];
	if (caseElements) {
		for (var i = 0; i < caseElements.length; i++) {// 四个图形元素
			if (caseElements[i].isSelected == true) {// 被选中的元素
				selection.push(i);
			} else if (caseElements[i].isSelected == false
					&& caseElements[i].children != null
					&& caseElements[i].children.length !== 0) {
				var childrens = caseElements[i].children;
				for (var k = 0; k < childrens.length; k++) {
					if (childrens[k].isSelected == true) {
						selection.push(i);
						selection.push(k);// 选中的子元素
					}
				}
			}
		}
	}
	return selection;
}

// 获取当前鼠标点击位置信息
function getEventPosition(ev) {
	var x = 0;
	var y = 0;
	if (ev.layerX || ev.layerX == 0) {
		x = ev.layerX;
		y = ev.layerY;
	} else if (ev.offsetX || ev.offsetX == 0) { // Opera
		x = ev.offsetX;
		y = ev.offsetY;
	}
	return {
		x : x,
		y : y
	};
}

// 根据当前坐标点返回选中的元素
function getSelectionElementByPoint(p, caseElements, elementTypes) {
	var selection = [];
	if (caseElements) {
		for (var i = 0; i < caseElements.length; i++) {// 图形区域选中
			var childrens = caseElements[i].children;
			var type = caseElements[i].type;
			var x = caseElements[i].x;
			var y = caseElements[i].y;
			caseElements[i].selectArea = -1;
			if (type == "012") {
				// 判断距离圆心（x,580）的距离小于半径20
				var calX = p.x - x;
				var calY = p.y - 580;
				if (Math.pow((calX * calX + calY * calY), 0.5) <= 20) {
					caseElements[i].isSelected = true;
					selection.push(caseElements[i]);
				} else {
					caseElements[i].isSelected = false;
				}
			} else if (type == "014") {
				// 判断选中区域在矩形框中时为选中
				if (p.x < x + 35 && p.x >= x - 35 && p.y >= 570 && p.y <= 600) {
					caseElements[i].isSelected = true;
					selection.push(caseElements[i]);
				} else {
					caseElements[i].isSelected = false;
				}
			} else if (type == "011") {
				// 条件轴选中区域：0、改变条件轴位置；1、选中右边线，可拉宽条件轴；2、点击三角区域，切换折叠条件轴显示
				var objWidth = caseElements[i].width;
				// 条件轴限定区域的可拖拽区域判定
				var xs1 = (caseElements[i].x - 20) + (objWidth - 10);
				var xs2 = (caseElements[i].x - 20) + objWidth;
				var ys1 = 110;
				var ys2 = elementTypes[elementTypes.length - 1].y2;
				if (p.x >= x - 40 && p.y <= y && p.x <= x && p.y >= y - 20) {// 改变条件轴位置
					caseElements[i].isSelected = true;
					caseElements[i].selectArea = 1;
					selection.push(caseElements[i]);
				} else if (p.x >= (x - 40) && p.x <= x && p.y > 90
						&& p.y <= 110) {
					// 三角形点击效果，三角形变成绿色，折叠矩形区域
					caseElements[i].isSelected = true;
					caseElements[i].selectArea = 2;
					selection.push(caseElements[i]);
				} else if (p.x >= xs1 && p.x <= xs2 && p.y >= ys1 && p.y <= ys2) {// 改变条件轴限定区域
					caseElements[i].isSelected = true;
					caseElements[i].selectArea = 0;
					selection.push(caseElements[i]);
				} else {
					caseElements[i].isSelected = false;
				}
				if (childrens) {
					// 矩形操作
					for (var j = 0; j < childrens.length; j++) { // 小矩形图形选中
						var x = childrens[j].x;
						var y = childrens[j].y;
						var width = childrens[j].width;
						var height = childrens[j].hight;
						// 当点击的位置正好是元素的x1,x2,y1,y2之间时，让小矩形元素可拖拽
						if (p.x >= x && p.y >= y && p.x <= (x + width)
								&& p.y <= y + height) {
							caseElements[i].children[j].isSelected = true;
							selection.push(caseElements[i].children[j]);
						} else {
							caseElements[i].children[j].isSelected = false;
						}
					}

				}
			}
		}
	}
	return selection;
}

function initButton(status) {
	if (roleButton().indexOf("csxlsh") != -1 && status == 1) {// 测试序列为提交未审核才展示审核按钮
		$('#Audit').removeAttr("hidden");
		$('#save').attr("hidden", 'hidden');
		$('#submit').attr("hidden", 'hidden');
		$('#delete').attr("hidden", 'hidden');
	}
	if (roleButton().indexOf("csxlbj") != -1 && status == 0 || status == 3) {// 测试序列为未提交才展示保存，提交等按钮
		$('#Audit').attr("hidden", 'hidden');
		$('#save').removeAttr("hidden");
		$('#submit').removeAttr("hidden");
		$('#delete').removeAttr("hidden");
	}

	if (roleButton().indexOf("jbylsh") != -1 && status == 2) {// 基本用例为提交未审核才展示审核按钮
		$('#Audit').attr("hidden", 'hidden');
		$('#save').attr("hidden", 'hidden');
		$('#submit').attr("hidden", 'hidden');
		$('#delete').attr("hidden", 'hidden');
	}
}
function rightParameter() {// 根据用户权限判断让右侧的参数修改和不可修改
	if ($("#save").attr("hidden") == undefined) {// 有权限时功能可用
		$("#outParameters select").removeAttr("disabled");
		$("#outParameters input").removeAttr("readOnly");
		
		$("#elementContents select").removeAttr("disabled");
		$("#elementContents input").removeAttr("readOnly");
		
		$("#outParameter select").removeAttr("disabled");
		$("#outParameter input").removeAttr("readOnly");
	} else {// 没有权限时，按钮禁用，功能隐藏
		$("#outParameters input").attr("readOnly", "true");
		$("#outParameters select").attr("disabled", "disabled");
		
		$("#elementContents input").attr("readOnly", "true");
		$("#elementContents select").attr("disabled", "disabled");
		
		$("#outParameter input").attr("readOnly", "true");
		$("#outParameter select").attr("disabled", "disabled");
	}
}
function hideRight() {// 隐藏右侧属性展示区域
	var date = $("#hideRight").attr("data");
	if (date == 1) {// 不隐藏
		$("#hideRight").attr("class", "glyphicon glyphicon-chevron-left");
		$("#hideRight").attr("title", "点击隐藏属性展示区域");
		$("#contentRight").css("display", "block");
		$("#content").css("width", "calc(100% - 245px)");
		$("#hideRight").attr("data", 2);
		return false;
	}
	if (date == 2) {// 隐藏
		$("#hideRight").attr("class", "glyphicon glyphicon-chevron-right");
		$("#hideRight").attr("title", "点击展示属性展示区域");
		$("#contentRight").css("display", "none");
		$("#content").css("width", "calc(100% - 450px)");
		$("#hideRight").attr("data", 1);
		return false;
	}
}

// 点击定位后，显示对应的站信号
function drawStationView() {
	showLineData(sltCanvas, id, drection);
}

// 切换数据版本
function shujuVersionFun(e) {
	console.log(e.value);
}
/**
 * 起始站输入拼音简写变化事件
 * 
 * @param e
 *            拼音简写输入框
 */
function startStationPYChangeSquence(e) {
	// 根据输入框的值从后台查询出相关车站信息
	$.ajax({
		url : '../../../basecase/getStationByPinYin',
		type : "POST",
		data : {
			fileId : yxzzId,
			pinYin : e.value,
			type : 1
		},
		success : function(obj) {
			if (obj.flag == 0) {
				stationList = obj.content;
				$("select[name='" + e.name + "']").empty();
				if ($("select[name='" + e.name + "']").length > 0) {
					if (stationList.length > 0) {
						$("select[name='" + e.name + "']").append(
								new Option("请选择", "请选择"));
						for (var i = 0; i < stationList.length; i++) {
							$("select[name='" + e.name + "']").append(
									new Option(stationList[i].name,
											stationList[i].stationNumber));
						}
					}
				}
			} else {
				danger(obj.errorInfo + "!");
			}
		}
	});
}
/**
 * 起始站输入拼音简写变化事件
 * 
 * @param e
 *            拼音简写输入框
 */
function stopStationPYChangeSquence(e,type) {
	// 根据输入框的值从后台查询出相关车站信息
	$.ajax({
		url : '../../../basecase/getStationByPinYin',
		type : "POST",
		data : {
			fileId : yxzzId,
			pinYin : e.value,
			type : 2
		},
		success : function(obj) {
			if (obj.flag == 0) {
				var endstationList = obj.content;
				if(type =='0'){
					$("select[name='007004014']").empty();
					if ($("select[name='007004014']").length > 0) {
						if (endstationList.length > 0) {
							$("select[name='007004014']").append(
									new Option("请选择", "请选择"));
							for (var i = 0; i < endstationList.length; i++) {
								$("select[name='007004014']").append(
										new Option(endstationList[i].name,
												endstationList[i].stationNumber));
							}
						}
					}
				}
				if(type =='1'){
					$("select[name='001002001']").empty();
					if ($("select[name='001002001']").length > 0) {
						if (endstationList.length > 0) {
							$("select[name='001002001']").append(
									new Option("请选择", "请选择"));
							for (var i = 0; i < endstationList.length; i++) {
								$("select[name='001002001']").append(
										new Option(endstationList[i].name,
												endstationList[i].stationNumber));
							}
						}
					}
				}
				
				if(type =='2'){
					$("select[name='001003001']").empty();
					if ($("select[name='001003001']").length > 0) {
						if (endstationList.length > 0) {
							$("select[name='001003001']").append(
									new Option("请选择", "请选择"));
							for (var i = 0; i < endstationList.length; i++) {
								$("select[name='001003001']").append(
										new Option(endstationList[i].name,
												endstationList[i].stationNumber));
							}
						}
					}
				}
			}
		}
	});
}
function locationClickFun() {
	if (!$('#positionSelect').val() || $('#positionSelect').val() == 0) {
		danger("请选择发车方向!");
	} else {
		showLineData(dataCanvas, sequenceData.dataVersion, $(
				'#positionSelect').val());
	}
}

/*******************************************************************************
 * 起始站选择变化事件
 * 
 * @param e
 */
function startStationChange(e) {
	// 根据输入框的值从后台查询出相关车站信息
	startStation = e.value;
	for (var i = 0; i < stationList.length; i++) {
		if (startStation == stationList[i].stationNumber) {
			var site = stationList[i].site;
			var directionList = stationList[i].direction;
			$("select[name='007004011']").empty();// 站场名
			for (var j = 0; j < site.length; j++) {
				$("select[name='007004011']").append(
						new Option(site[j].name, site[j].id));
			}
			$("select[name='007004011']").get(0).selectedIndex = 0;// 默认选中第一个
			$("select[name='007004011']").change();
			$("select[name='007004013']").empty();
			$("select[name='007004013']").append(new Option("请选择", "请选择"));// 发车方向
			for (var k = 0; k < directionList.length; k++) {
				$("select[name='007004013']").append(
						new Option(directionList[k].name, directionList[k].id));
			}
		}
	}

	saves(e);
}

/*******************************************************************************
 * 发车方向变化事件
 * 
 * @param e
 */
function directionChange(e) {
	direction = e.value;
	for (var i = 0; i < stationList.length; i++) {
		if (startStation == stationList[i].stationNumber) {
			var directionList = stationList[i].direction;
			for (var j = 0; j < directionList.length; j++) {
				if (direction == directionList[j].id) {
					var runningPathList = directionList[j].runningPath;
					$("select[name='007004015']").empty();
					$("select[name='007004015']").append(new Option("无", "0"));// 运行径路选择
					for (var k = 0; k < runningPathList.length; k++) {
						$("select[name='007004015']").append(
								new Option(runningPathList[k].name,
										runningPathList[k].id));
					}
					$("select[name='007004015']").change();
				}
			}
		}
	}

	saves(e);
}

// 信号机 的canvas的点击
function signlCanvasClick(e) {
	saves(null);
	var p = getEventPosition(e);// 当前点击位置的坐标
	// 根据当前点击点的坐标获取点击的元素并设置选中
	var selection = getSinglDetailByLocation(p);
	$("#outParameters").empty();// 每次点击都会清空数据展示区域
	if (selection) {// 如果有元素被选中
		if (selection.dic) {
			var div = "";
			div = ("<div>" + "<span>" + "站名" + "</span>"
					+ "<select disabled='disabled'><option>"
					+ selection.trainstation.name + "</option></select>" + "</div>");
			$("#outParameters").append("" + div + "");
		} else {
			if (selection.teleseme.type != 5) {
				var div = "";
				div = ("<div>" + "<span>" + selection.teleseme.typeName
						+ "</span>" + "<select disabled='disabled'><option>"
						+ selection.teleseme.name + "</option></select>" + "</div>");
				$("#outParameters").append("" + div + "");
			} else {
				showSelectBySelect(getSinglStation(selection));
			}
		}
	}

	rightParameter();// 根据用户权限判断让右侧的参数修改和不可修改
}

// 根据点击的坐标获取当前信号机的信息
function getSinglDetailByLocation(p) {
	var selectObj = null;
	for (var i = 0; i < trationLineData.length; i++) {
		if (trationLineData[i].x) {
			if (p.x >= trationLineData[i].x && p.y >= trationLineData[i].y
					&& p.x <= trationLineData[i].x + trationLineData[i].width
					&& p.y <= trationLineData[i].y + trationLineData[i].width) {
				selectObj = trationLineData[i];
				break;
			}
		}
	}
	return selectObj;
}

// 根据name获取当前出站信号记得站信息
function getSinglStation(selection) {
	var obj = null;
	var index = 0;
	for (var j = 0; j < trationLineData.length; j++) {
		if (trationLineData[j].teleseme) {
			if (trationLineData[j].teleseme.type == 5) {
				if (selection.teleseme.name == trationLineData[j].teleseme.name) {
					index = j;
					break;
				}
			}
		}
	}

	for (var j = index; j >= 0; j--) {
		if (trationLineData[j].type == 1) {
			obj = trationLineData[j];
			break;
		}
	}
	return obj;
}

// 根据选中的站名，显示对应的下拉框
function showSelectBySelect(selection) {
	var div = "";
	div = ("<div>" + "<span>" + "出站信号机" + "</span>" + "<select id='"
			+ selection.trainstation.id + "'>" + "</select>" + "</div>");
	$("#outParameters").append("" + div + "");
	if (selection.dic) {
		for (var i = 0; i < selection.dic.length; i++) {
			$("#" + selection.trainstation.id).append(
					"<option>" + selection.dic[i].teleseme.name + "</option>");
		}
	}
}

// Ctrl+c ctrl+v 快捷键复制粘贴功能
function keydown(e) {
	return;
	if (!sequenceEditBool) {
		return;
	}
	if (event.ctrlKey == 1) {
		if (document.all) {
			k = e.keyCod;
		} else {
			k = e.which;
		}
		if (k == 86) {// 粘贴
			book("粘贴成功！");
			getBaseCaseById(sltCanvasCopyObj[copyCaseSelectIndex - 1].caseId,
					sltCanvasCopyObj[copyCaseSelectIndex - 1].name);
		}
		if (k == 67) {// 复制
			book("复制成功！");
			clcikAddSequeceBool = true;
			sltCanvasCopyObj = [];
			sltCanvasCopyObj = [].concat(JSON.parse(JSON
					.stringify(sltCanvasSelectObj)));
		}
	}
}

// 基本用例中的快捷键复制粘贴和删除添加成功提示
function book(str) {
	$('#alertText').html(str);
	$('#myModal').modal('show');
	setTimeout(function() {
		$("#myModal").modal("hide");
	}, 1200);
}

// 绘制图形,当stateType：1：为选中，2时：为有外部参数，3:执行失败；selected：true时为选中，false为不选中
function drawProcessChart(caseElements) {
	for (var i = 0; i < caseElements.length; i++) {
		//判断是否有外部参数，有外部参数高亮显示
		for(var j = 0;j<caseElements[i].attributes.length;j++){
			if(caseElements[i].attributes[j].required == '1'){
				caseElements[i].stateType = 2;
			}
		}
		setDrawSize(caseElements[i]);
		if (caseElements[i].leve == '1') {// 控件
			var diagonal = baseTDrawCanvas.getDrawing('diagonal', {
				obj : {
					text : caseElements[i].name,
					x : caseElements[i].x,
					y : caseElements[i].y,
					color : '#7F7F7F',
					width : rectWidth,
					height : rectHeight,
					selected : caseElements[i].selected,
					stateType:caseElements[i].stateType
				}
			});
			diagonal.draw();
		} else if (caseElements[i].leve == '2') {// 分支或者循环
			if (caseElements[i].type == '015') {// 分支
				var coditionCount = 0;
				if (caseElements[i].conditionList) {
					coditionCount = caseElements[i].conditionList.length;
				}
				var branchCell = baseTDrawCanvas.getDrawing('branch', {
					x : caseElements[i].x,
					y : caseElements[i].y,
					width : caseElements[i].width,
					height : caseElements[i].height,
					bottomLeftWidth : caseElements[i].leftWidth,
					bottomRightWidth : caseElements[i].rightWidth,
					filledColor : titleBackGround,
					selected : caseElements[i].selected,
					conditionPostion : conditionPostion,
					conditionSpace : conditionSpace,
					conditionCount : coditionCount,
					conditionList : caseElements[i].conditionList,
					stateType:caseElements[i].stateType
				});
				branchCell.draw();
				drawProcessChart(caseElements[i].leftChildrens);
				drawProcessChart(caseElements[i].rightChildrens);
			} else if (caseElements[i].type == '016') {// 循环
				var coditionCount = 0;
				if (caseElements[i].conditionList) {
					coditionCount = caseElements[i].conditionList.length;
				}
				var loopCell = baseTDrawCanvas.getDrawing('loop', {
					x : caseElements[i].x,
					y : caseElements[i].y,
					width : caseElements[i].width,
					height : caseElements[i].height,
					isLabel : false,
					filledColor : titleBackGround,
					selected : caseElements[i].selected,
					conditionPostion : conditionPostion,
					conditionSpace : conditionSpace,
					conditionCount : coditionCount,
					conditionList : caseElements[i].conditionList,
					stateType:caseElements[i].stateType
				});
				loopCell.draw();
				drawProcessChart(caseElements[i].childrens);
			}
		} else if (caseElements[i].leve == '3') {// 条件轴

		}
	}
}

// 设置caseElements数据中的空间大小和位置
function setDrawSize(obj) {
	// 设置控件的大小
	setCaseSize(obj);
	// 设置控件的位置
	setCaseArray(caseElements);
}
// 设置控件的大小
function setCaseSize(obj) {
	var size = new Object;
	var heightCount = 0;
	var widthCount = 0;
	if (obj.leve == '1') {
		heightCount = heightCount + rectHeight;
		widthCount = rectWidth;
	} else if (obj.leve == '2') {
		heightCount = heightCount + banchLoopTitleHeight;
		var widthLeft = 0;
		var widthRight = 0;
		if (obj.type == '015') {
			var leftHeight = betweenTool;
			var rightHeight = betweenTool;
			for (var p = 0; p < obj.leftChildrens.length; p++) {
				var returnSize = setCaseSize(obj.leftChildrens[p]);
				leftHeight = leftHeight + returnSize.height;
				if (!obj.leftChildrens[p].width) {
					obj.leftChildrens[p].width = getWidth(obj.leftChildrens[p]);
				}
				if (widthLeft < returnSize.width) {
					widthLeft = returnSize.width;
				}
			}
			for (var q = 0; q < obj.rightChildrens.length; q++) {
				var returnSize = setCaseSize(obj.rightChildrens[q]);
				rightHeight = rightHeight + returnSize.height;
				if (!obj.rightChildrens[q].width) {
					obj.rightChildrens[q].width = getWidth(obj.rightChildrens[q]);
				}
				if (widthRight < returnSize.width) {
					widthRight = returnSize.width;
				}
			}
			if (leftHeight >= rightHeight) {
				heightCount = heightCount + leftHeight;
			} else {
				heightCount = heightCount + rightHeight;
			}
			if (widthLeft < banchLoopWidth) {
				widthLeft = banchLoopWidth;
			}
			if (widthRight < banchLoopWidth) {
				widthRight = banchLoopWidth;
			}
			widthCount = widthLeft + widthRight;
			obj.leftWidth = widthLeft;
			obj.rightWidth = widthRight;
		} else if (obj.type == '016') {
			heightCount = heightCount + betweenTool;
			for (var i = 0; i < obj.childrens.length; i++) {
				var returnSize = setCaseSize(obj.childrens[i]);
				heightCount = heightCount + returnSize.height;
				if (!obj.childrens[i].width) {
					obj.childrens[i].width = getWidth(obj.childrens[i]);
				}
				if (widthCount < returnSize.width) {
					widthCount = returnSize.width;
				}
			}
			if (widthCount < banchLoopWidth) {
				widthCount = banchLoopWidth;
			}
		}
	}
	obj.height = heightCount;
	obj.width = widthCount;
	size.height = heightCount + betweenTool;
	size.width = widthCount + betweenTool + betweenTool;
	return size;
}
// 设置控件的位置
function setCaseArray(objArray) {
	var MARGIN = betweenTool;
	var x = initLocation.x;
	var y = initLocation.y;
	for (var i = 0; i < objArray.length; i++) {
		var size = setCasePostion(objArray[i], x, y);
		y = y + size.cy + MARGIN;
	}
}
// 设置控件的位置
function setCasePostion(obj, X, Y) {
	var MARGIN = betweenTool;
	var returnSize = new Object;
	returnSize.cx = 0;
	returnSize.cy = 0;
	obj.x = X;
	obj.y = Y;
	if (obj.leve == '1') {
		returnSize.cx = rectWidth;
		returnSize.cy = rectHeight;
	} else if (obj.leve == '2') {
		if (obj.type == '015') {
			var xMaxLeft = 0;
			var yLeft = Y + banchLoopTitleHeight + MARGIN;
			if (obj.leftChildrens.length <= 0) {
				xMaxLeft = banchLoopWidth;
			}
			for (var i = 0; i < obj.leftChildrens.length; i++) {
				var size = setCasePostion(obj.leftChildrens[i], X + MARGIN,
						yLeft);
				yLeft = yLeft + size.cy + MARGIN;
				if (xMaxLeft < MARGIN + size.cx + MARGIN)
					xMaxLeft = MARGIN + size.cx + MARGIN;
			}
			var xMaxRight = 0;
			if (obj.rightChildrens.length <= 0) {
				xMaxRight = banchLoopWidth;
			}
			var yRight = Y + banchLoopTitleHeight + MARGIN;
			for (var i = 0; i < obj.rightChildrens.length; i++) {
				var size = setCasePostion(obj.rightChildrens[i], X + xMaxLeft
						+ MARGIN, yRight);
				yRight = yRight + size.cy + MARGIN;
				if (xMaxRight < MARGIN + size.cx + MARGIN)
					xMaxRight = MARGIN + size.cx + MARGIN;
			}
			returnSize.cx = xMaxLeft + xMaxRight;
			returnSize.cy = (yLeft > yRight ? yLeft : yRight) - Y;
		} else if (obj.type == '016') {
			returnSize.cx = banchLoopWidth;
			returnSize.cy = banchLoopTitleHeight + MARGIN;
			var y = Y + banchLoopTitleHeight + MARGIN;
			for (var i = 0; i < obj.childrens.length; i++) {
				var size = setCasePostion(obj.childrens[i], X + MARGIN, y);
				y = y + size.cy + MARGIN;
				if (returnSize.cx < MARGIN + size.cx + MARGIN)
					returnSize.cx = MARGIN + size.cx + MARGIN;
			}
			returnSize.cy = y - Y;
		}
	}
	return returnSize;
}
// 获取空间的初始大小
function getWidth(obj) {
	var w = 0;
	if (obj.leve == '1') {// 小矩形控件
		w = rectWidth;
	} else {
		if (obj.type == '015') {// 分支
			w = banchLoopWidth * 2;
		} else if (obj.type == '016') {// 循环
			w = banchLoopWidth;
		}
	}
	return w;
}

//鼠标点击
function canvasDownFun(ev) {
	ev.preventDefault();
	var x = ev.offsetX;
	var y = ev.offsetY;
	getClickObj(x, y);
}

//获取当前点击坐标的对象
function getClickObj(x, y) {
	//重置所有元素为不选中状态
	resetSelected();
	//当前选中元素的id
	selectTargetId = '';
	//鼠标点击后，把通过子元素寻找父元素的变量置空
	childToParentData = null;
	//递归获取当前选中的元素
	for (var i = 0; i < caseElements.length; i++) {
		selectTargetId = getTargetObj(caseElements[i], x, y, null, null, i, i);
		if (selectTargetId != '') {
			break;
		}
	}
}

//递归获取当前选中的元素
function getTargetObj(obj, x, y, parentObjArray, parentObj, index, parentIndex) {
	var selectIndex = '';
	if (obj.leve == '1') {// 小矩形
		if (parentObj) {
			if (x > (obj.x)
					&& x < (obj.x + obj.width + betweenTool)) {
				if (y > (obj.y - betweenTool) && y < obj.y) {// 矩形的上方，
					selectIndex = parentObj.id;
					parentObj.selected = true;
					selectTargetData = parentObj;
				}else if (y > obj.y && y < (obj.y + obj.height)) {// 矩形的下方，
					selectIndex = obj.id;
					obj.selected = true;
					selectTargetData = obj;
				} else if (y > (obj.y + obj.height) && y < (obj.y + obj.height+betweenTool)) {// 矩形内部或者矩形下方
					selectIndex = parentObj.id;
					parentObj.selected = true;
					selectTargetData = parentObj;
				}
			}
		} else {
			if (x > (obj.x)
					&& x < (obj.x + obj.width)) {
				if (y > obj.y - betweenTool && y < obj.y) {// 矩形的上方，
					
				} else if (y > obj.y && y < (obj.y + obj.height)) {// 矩形内部
					selectIndex = caseElements[parentIndex].id;
					selectTargetData = caseElements[parentIndex];
					caseElements[parentIndex].selected = true;
				}
			}
		}
	} else {
		if (obj.type == '015') {// 分支
			if ((x>(obj.x - betweenTool) && x<(x+obj.width+betweenTool)&& y>(obj.y - betweenTool)&& y<obj.y)
					|| (x>(obj.x - betweenTool)&&x<obj.x&&y>(obj.y - betweenTool)&&y<(obj.y+obj.height+betweenTool))
					|| (x>(obj.x+obj.width)&&x<(obj.x+obj.width+betweenTool)&&y>(obj.y - betweenTool)&&y<(obj.y+obj.height+betweenTool))
					|| (x>(obj.x - betweenTool) && x<(x+obj.width+betweenTool)&& y>(obj.y + obj.height)&& y<(obj.y + obj.height+betweenTool))){
				if (parentObj) {
					selectIndex = parentObj.id;
					parentObj.selected = true;
					selectTargetData = parentObj;
				}else{
					selectIndex = caseElements[parentIndex].id;
					selectTargetData = caseElements[parentIndex];
					caseElements[parentIndex].selected = true;
				}
			}else{
				if(x>obj.x&& x<obj.x + obj.width && y>obj.y && y<obj.y + banchLoopTitleHeight){//分支头
					var titleData = getTitleDataByPostion(obj,x,y);
					if(titleData == null){
						selectIndex = obj.id;
						obj.selected = true;
						selectTargetData = obj;
					}else{
						selectIndex = titleData.id;
						selectTargetData = titleData;
						//当选中软件版本换装的条件控件时，弹出提示框显示软件版本
						if(titleData.code == "009008"){
							showSoftChangeList(titleData);
						}
					}
				}else if(x>obj.x && x<obj.x + obj.leftWidth && y>obj.y+banchLoopTitleHeight && y<obj.y + obj.height){//左侧
					if (obj.leftChildrens.length <= 0) {
						selectIndex = obj.id;
						obj.selected = true;
						selectTargetData = obj;
					} else {
						for (var i = 0; i < obj.leftChildrens.length; i++) {
							selectIndex = getTargetObj(obj.leftChildrens[i], x,
									y, obj.leftChildrens, obj, i, parentIndex);
							if (selectIndex != '') {
								break;
							}
						}
					}
				}else if(x>obj.x + obj.leftWidth && x<obj.x + obj.width && y>obj.y+banchLoopTitleHeight && y<obj.y + obj.height){//左侧
					if (obj.rightChildrens.length <= 0) {
						selectIndex = obj.id;
						obj.selected = true;
						selectTargetData = obj;
					} else {
						for (var i = 0; i < obj.rightChildrens.length; i++) {
							selectIndex = getTargetObj(obj.rightChildrens[i],
									x, y, obj.rightChildrens, obj, i,
									parentIndex);
							if (selectIndex != '') {
								break;
							}
						}
					}
				}
			}
		} else if (obj.type == '016') {// 循环
			if (x > obj.x&& x < (obj.x + obj.width) && y>obj.y && y<(obj.y+obj.height)) {
				if (y > obj.y && y < (obj.y + banchLoopTitleHeight)) {
					var titleData = getTitleDataByPostion(obj,x,y);
					if(titleData == null){
						selectIndex = obj.id;
						obj.selected = true;
						selectTargetData = obj;
					}else{
						selectIndex = titleData.id;
						selectTargetData = titleData;
						//当选中软件版本换装的条件控件时，弹出提示框显示软件版本
						if(titleData.code == "009008"){
							showSoftChangeList(titleData);
						}
					}
				} else if (y > (obj.y + banchLoopTitleHeight)
						&& y < (obj.y + obj.height)) {
					if (obj.childrens.length <= 0) {
						selectIndex = obj.id;
						obj.selected = true;
						selectTargetData = obj;
					} else {
						for (var i = 0; i < obj.childrens.length; i++) {
							selectIndex = getTargetObj(obj.childrens[i], x, y,
									obj.childrens, obj, i, parentIndex);
							if (selectIndex != '') {
								break;
							}
						}
					}
				}
			}else if ((x>(obj.x - betweenTool) && x<(x+obj.width+betweenTool)&& y>(obj.y - betweenTool)&& y<obj.y)
					|| (x>(obj.x - betweenTool)&&x<obj.x&&y>(obj.y - betweenTool)&&y<(obj.y+obj.height+betweenTool))
					|| (x>(obj.x+obj.width)&&x<(obj.x+obj.width+betweenTool)&&y>(obj.y - betweenTool)&&y<(obj.y+obj.height+betweenTool))
					|| (x>(obj.x - betweenTool) && x<(x+obj.width+betweenTool)&& y>(obj.y + obj.height)&& y<(obj.y + obj.height+betweenTool))){
				if (parentObj) {
					selectIndex = parentObj.id;
					parentObj.selected = true;
					selectTargetData = parentObj;
				}else{
					selectIndex = caseElements[parentIndex].id;
					selectTargetData = caseElements[parentIndex];
					caseElements[parentIndex].selected = true;
				}
			}
		}
	}
	return selectIndex;
}

//根据控件容器头部的点击位置，判断是否有元素
function getTitleDataByPostion(obj,x,y){
	var data = null;
	var relativeX  = x - obj.x - conditionPostion.x;
	var relativeY = y - obj.y - conditionPostion.y;
	if(obj.conditionList == null){
		return null;
	}
	for(var i = 0;i<obj.conditionList.length;i++){
		if((relativeX>=i*23) && (relativeX<=20+23*i) &&relativeY>=0 && relativeY<=20){
			data = obj.conditionList[i];
			obj.conditionList[i].selected = true;
			break;
		}
	}
	return data;
}

// 重置caseElements中控件的selected为false，为不选中状态
function resetSelected() {
	for (var i = 0; i < caseElements.length; i++) {
		loopReSetSelected(caseElements[i]);
	}
}
//递归重置caseElements中控件的selected为false，为不选中状态
function loopReSetSelected(obj) {
	obj.selected = false;
	if (obj.leve == '1') {
	} else if (obj.leve == '2') {
		for(var i = 0;i<obj.conditionList.length;i++){
			obj.conditionList[i].selected = false;
		}
		if (obj.type == '015') {
			for (var i = 0; i < obj.leftChildrens.length; i++) {
				loopReSetSelected(obj.leftChildrens[i]);
			}
			for (var i = 0; i < obj.rightChildrens.length; i++) {
				loopReSetSelected(obj.rightChildrens[i]);
			}
		} else if (obj.type == '016') {
			for (var i = 0; i < obj.childrens.length; i++) {
				loopReSetSelected(obj.childrens[i]);
			}
		}
	}
}

//根据children的id获取父节点的数据childToParentData
function getParentDataByChild(childId,nameStr){
	for(var i = 0;i<caseElements.length;i++){
		childToParentData = getParentDataByChildLoop(caseElements[i],childId,nameStr);
		if(childToParentData!=null){
			break;
		}
	}
	context.clearRect(0, 0, baseCaseCanvas.width, baseCaseCanvas.height);
	for (var i = 0; i < caseElements.length; i++) {
		setDrawSize(caseElements[i]);
	}
	resetCanvasHeight();
	drawProcessChart(caseElements);
}
function getParentDataByChildLoop(obj,childId,nameStr){
	for(var i = 0;i<obj.attributes.length;i++){
		if(obj.attributes[i].id == childId){
			childToParentData = obj;
			obj.name =nameStr;
			break;
		}
	}
	if(childToParentData!=null){
		return;
	}
	if(obj.leve == '1'){
		
	}else{
		if(obj.type == '015'){
			for(var j=0;j<obj.leftChildrens.length;j++){
				getParentDataByChildLoop(obj.leftChildrens[j],childId,nameStr);
			}
			for(var j=0;j<obj.rightChildrens.length;j++){
				getParentDataByChildLoop(obj.rightChildrens[j],childId,nameStr);
			}
		}else if(obj.type == '016'){
			for(var j=0;j<obj.childrens.length;j++){
				getParentDataByChildLoop(obj.childrens[j],childId,nameStr);
			}
		}
	}
}

//根据select的code获取当前select下拉框的内容
function getSelectListByCode(code){
	var dict = [];
	for(var i = 0;i<selectAllListData.length;i++){
		if(selectAllListData[i].code == code){
			dict = selectAllListData[i].dict;
			break;
		}
	}
	return dict;
}

//获取数据中下拉框的数据
function getSelectListData(){
	$.ajax({
		async:false,
		cache:false,
		type:'POST',
		dataType:'json',
		url:'../../../basecase/getAllDictionary',
		error : function(data) {
			danger(data.errorInfo);
		},
		success : function(data) {
			if(data.flag == 0){
				console.log(data.content);
				//获取到下拉框的所有数据
				selectAllListData = data.content;
			}else{
				danger(data.errorInfo);
			}
		}
	});
}
//删除元素或者清空元素后，重置右侧的控件信息
function resetMsg() {
	$("#caseNamee").empty();
	$("#elementContents").empty();
	$('#conDescription').empty(); // 清空控件说明描述内容
	$('#outParameter').empty();// 清空外部参数内容
}

function resetCanvasHeight(){
	if (caseElements.length > 0) {
		if(caseElements[caseElements.length - 1] && caseElements[caseElements.length - 1].y){
			if((caseElements[caseElements.length - 1].y + caseElements[caseElements.length - 1].height)+150 > 750){
				baseCaseCanvas.height = caseElements[caseElements.length - 1].y
				+ caseElements[caseElements.length - 1].height + 150;
			}
		}else if(caseElements[caseElements.length - 2] && caseElements[caseElements.length - 2].y){
			if((caseElements[caseElements.length - 2].y + caseElements[caseElements.length - 2].height)+150 > 750){
				baseCaseCanvas.height = caseElements[caseElements.length - 2].y
				+ caseElements[caseElements.length - 2].height + 150;
			}
		}
	}
}
//获取条件控件中数据项的下拉切换时的数据状态信息
function getShuJuXiangMsg(){
	$.ajax({
		async:false,
		cache:false,
		type:'POST',
		dataType:'json',
		url:'../../../basecase/getCondition',
		error : function(data) {
			danger(data.errorInfo);
		},
		success : function(data) {
			if(data.flag == 0){
				console.log(data);
				shuJuAllDataArray = data.content;
				// 跳转到页面后,通过页面链接中截取的序列ID展示当前测试序列内的基本用例并绘制
				showTestSequence(addSequenceId);
			}else{
				danger(data.errorInfo);
			}
		}
	});
}
//设置日期时间控件
function Datetime(shuxing, id) {
	$('#datetimepicker2').datetimepicker({
		language : 'zh-CN',// 显示中文
		format : 'yyyy-mm-dd hh:ii:ss',// 显示格式
		minView : 0,// 设置只显示到月份
		initialDate : new Date(),
		autoclose : true,// 选中自动关闭
		todayBtn : true,// 显示今日按钮
		locale : moment.locale('zh-cn'),
	}).on('changeDate', function(ev) {
		$('#' + id).val(formatDateTime(Number(ev.date.valueOf())));
		saves(null);
	});

	// 默认获取当前日期
	if (shuxing.value) {
		if (shuxing.value != -1) {
			document.getElementById(id).value = setTimeToTimeFormat(shuxing.value);
		} else {
			document.getElementById(id).value = shuxing.value;
		}
	} else {
		document.getElementById(id).value = "-1";
	}

}
function formatDateTime(inputTime) {
	var date = new Date(inputTime);
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	m = m < 10 ? ('0' + m) : m;
	var d = date.getDate();
	d = d < 10 ? ('0' + d) : d;
	var h = date.getHours();
	h = h < 10 ? ('0' + h) : h;
	var minute = date.getMinutes();
	var second = date.getSeconds();
	minute = minute < 10 ? ('0' + minute) : minute;
	second = second < 10 ? ('0' + second) : second;
	return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}
function set_Time_value(th) {// th this用来获取属性值，ys就是整个元素对象
	if (!checkDateTime($(th).val())) {// 输入的时间格式校验
		$(th).val('-1');
		return;
	}
	saves(null);
}
//时间格式校验
function checkDateTime(date) {
	var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
	var r = date.match(reg);
	if (r != null || date == '-1') {
		return true;
	} else {
		warning("输入格式不正确，请按yyyy-MM-dd HH:mm:ss的格式输入！");
		return false;
	}
}
//根据时间数字转换为时间格式20180723140101 2018-07-24 13:35:08
function setTimeToTimeFormat(timeStr) {
	var timeFormat = "";
	var numArray = timeStr.split("");
	timeFormat = numArray[0] + numArray[1] + numArray[2] + numArray[3] + "-"
			+ numArray[4] + numArray[5] + "-" + numArray[6] + numArray[7] + " "
			+ numArray[8] + numArray[9] + ":" + numArray[10] + numArray[11]
			+ ":" + numArray[12] + numArray[13];
	return timeFormat;
}

//去除前台处理的dicMu
function reSetSendData(caseElements){
	var copyArray = [].concat(JSON.parse(JSON.stringify(caseElements)));
	for(var i = 0;i<copyArray.length;i++){
		reSetSendDataLoop(copyArray[i]);
	}
	
	return copyArray;
}
function reSetSendDataLoop(obj){
	for(var i = 0;i<obj.attributes.length;i++){
		obj.attributes[i].dicMu = [];
		if(obj.self_softChangeList){
			obj.self_softChangeList = [];
		}
	}
	
	for(var i = 0;i<obj.childrens.length;i++){
		reSetSendDataLoop(obj.childrens[i]);
	}
	
	for(var i = 0;i<obj.leftChildrens.length;i++){
		reSetSendDataLoop(obj.leftChildrens[i]);
	}
	for(var i = 0;i<obj.rightChildrens.length;i++){
		reSetSendDataLoop(obj.rightChildrens[i]);
	}
	
	if(obj.conditionList){
		for(var i = 0;i<obj.conditionList.length;i++){
			reSetSendDataLoop(obj.conditionList[i]);
		}
	}
}

//调取列车类型获取接口更新列车类型下拉内容以及车种标识联动更新下拉选项
//id:文件id
//trainType:列车类型值
//trainBZ:车种标识值
function getLKJTrainTypeSequence(id,value1,shuxing){
	var result = [];
	$.ajax({
		url : '../../../basecase/getTrainType',
		type : "POST",
		data :  {fileId: id},
		success : function(obj) {
			if(obj.flag==0){
				console.log(obj);
				 result = obj.content;
				 lclxArray = result;
				 shuxing.dicMu = lclxArray;
			}
			if(value1 == ""){
				value1 = "无";
			}
			$("select[name='007004004']")[0].options.length=0;//清空下拉内容，重新赋值
			$("select[name='007004004']").append("<option value='请选择' selected='selected'>请选择</option>");
			for (var i = 0; i < result.length; i++) {
				if(value1==result[i].id){
					$("select[name='007004004']").append("<option  selected='selected' value='" + result[i].id + "' >"
							+ result[i].name + "</option>");
				}else{
					$("select[name='007004004']").append("<option value='" + result[i].id + "' >"
							+ result[i].name + "</option>");
				}
				
			}
		},
		error : function(error) {
			console.log(error);
		}

	});	
}

//检查当前测试序列保存时外部参数是否已经填写
function checkAllCaseElements(sequenceInfo){
	var bool = true;
	for(var i = 0;i<sequenceInfo.length;i++){
		bool = checkOutParament(sequenceInfo[i].caseElement);
		if(!bool){
			break;
		}
	}
	return bool;
}

//检查测试序列中的基本用例的外部参数是否都填写
function checkOutParament(caseElement){
	var bool = true;
	for(var i = 0;i<caseElement.length;i++){
		bool = checkOutParamentLoop(caseElement[i]);
		if(!bool){
			break;
		}
	}
	return bool;
}
//检查测试序列中的基本用例的外部参数是否都填写
function checkOutParamentLoop(obj){
	var bool = true;
	for(var i = 0;i<obj.attributes.length;i++){
		if(obj.attributes[i].required == "1" && (obj.attributes[i].value == ""
			|| obj.attributes[i].value == "请选择"//下拉框的值为“请选择”时下拉框的值为空
				|| obj.attributes[i].value == "请输入"//文本输入框为“请输入”时文本输入框的值为空
					)){
			if(obj.attributes[i].code != "007004014" && obj.attributes[i].code != "001002003" && obj.attributes[i].code != "007004004"){//终止站名外部参数不在判断范围内，可以为空（贾楠）
				failMsg = '外部参数不能为空！';
				bool = false;
				return bool;
			}
		}
	}
	for(var i = 0;i<obj.childrens.length;i++){
		if(!checkOutParamentLoop(obj.childrens[i])){
			return false;
		}
	}
	for(var i = 0;i<obj.leftChildrens.length;i++){
		if(!checkOutParamentLoop(obj.leftChildrens[i])){
			return false;
		}
	}
	for(var i = 0;i<obj.rightChildrens.length;i++){
		if(!checkOutParamentLoop(obj.rightChildrens[i])){
			return false;
		}
	}
	return bool;
}

//设置当前数据版本的显示信息
function setDataVersion(){
	$.ajax({
		"url" : "../../../sequence/getLKLdataVersionById",
		"type" : "post",
		"data" : { 
			id:dataVersionCode
		},
		"dataType" : "json",
		"success" : function(result) {
			console.log(result);
			if(result.flag==0){
				$('#dataVersionLabel').html("数据版本 "+result.content.versionNumber+" "+result.content.versionTime);
			}else{
				warning(result.errorInfo);
			}
		},
		"error" : function(data) {
			warning(data.errorInfo);
		}
	});
}

//当选中软件版本换装的条件控件时，弹出提示框显示软件版本
function showSoftChangeList(data){
	console.log(selectTargetData);
	BootstrapDialog.show({
		title:"软件版本",
		draggable: true,
	    closable: false,
		message:$("<form class='form-inline' style='height:640px;'></form>")
		.load("softChangeBase.html"),
		buttons:[{
			icon : 'glyphicon glyphicon-check',
			label : '确定',
			cssClass : 'btn-primary',
			autospin : true,
			action : function(dialogRef) {
				saveSoftData(data);
				sequenceEditBool = true;// 释放复制粘贴快捷键
				dialogRef.close();
			}
		}, {
			label : '取消',
			action : function(dialogRef) {
				sequenceEditBool = true;// 释放复制粘贴快捷键
				dialogRef.close();
			}
		} ]
	});
}
//保存选中的软件版本
function saveSoftData(data){
	var changeObjs = [];
	// 根据软件id获取当前选中的文件id和换装位置信息并进行封装
	if (softIds.length > 0) {
		for (var i = 0; i < softIds.length; i++) {
			var changeObj = {};
			var softId = softIds[i];
			var fileObj = $("#" + softId + " select.signSelect");
			var fileId = "";
			if (fileObj.length > 0) {
				fileId = fileObj[0].value;
				changeObj.fileId = fileId;
				changeObj.id = softId;
			}
			if (fileId != "") {// 如果选择要更换的文件则查询当前选中的换装位置
				var softChangePosition = "";
				var selectdOption = $("#" + softId + " select.multipleSelect");
				if (selectdOption.length > 0) {
					for (var j = 0; j < selectdOption[0].length; j++) {
						if (selectdOption[0][j].selected) {
							softChangePosition += "1";
						} else {
							softChangePosition += "0";
						}
					}
				} else {
					softChangePosition = "0";
				}
				changeObj.position = softChangePosition;// 换装位置可为空
				changeObjs.push(changeObj);
			}
		}
		for(var i = 0;i<caseElements.length;i++){
			getSaveChangeLoop(caseElements[i],data,changeObjs);
		}
	}
}
function getSaveChangeLoop(obj,data,changeObjs){
	if(!obj.conditionList){
		return;
	}
	for(var j = 0;j<obj.conditionList.length;j++){
		if(obj.conditionList[j].id == data.id){
			obj.conditionList[j].self_softChangeList = changeObjs;
			obj.conditionList[j].attributes[1].value = JSON.stringify(changeObjs);
			break;
		}
	}
	if(obj.childrens.length){
		getSaveChangeLoop(obj.childrens,data,changeObjs);
	}
	if(obj.leftChildrens.length){
		getSaveChangeLoop(obj.leftChildrens,data,changeObjs);
	}
	if(obj.rightChildrens.length){
		getSaveChangeLoop(obj.rightChildrens,data,changeObjs);
	}
}

//根据列车类型的数据筛选出当前切换的列车类型的列车标志的id
function getLzbzByTranType(tranType){
	console.log(lclxArray);
	var id = "";
	for(var i = 0;i<lclxArray.length;i++){
		for(var j = 0;j<lclxArray[i].children.length;j++){
			if(lclxArray[i].children[j].id == tranType){
				id = lclxArray[i].children[j].lcbz;
				break;
			}
		}
	}
	return id;
}

//根据id设置选中控件
function setSelectedById(id) {
	//重置所有元素为不选中状态
	resetSelected();
	for (var i = 0; i < caseElements.length; i++) {
		loopSetSelectedById(caseElements[i],id);
	}
}
//根据id设置选中控件
function loopSetSelectedById(obj,id) {
	if (obj.leve == '1') {
		if(obj.id == id){
			obj.selected = true;
			selectTargetData = obj;
		}
	} else if (obj.leve == '2') {
		if(obj.id == id){
			obj.selected = true;
			selectTargetData = obj;
		}
		for(var i = 0;i<obj.conditionList.length;i++){
			if(obj.conditionList[i].id == id){
				obj.conditionList[i].selected = true;
				selectTargetData = obj.conditionList[i];
			}
		}
		if (obj.type == '015') {
			for (var i = 0; i < obj.leftChildrens.length; i++) {
				loopSetSelectedById(obj.leftChildrens[i],id);
			}
			for (var i = 0; i < obj.rightChildrens.length; i++) {
				loopSetSelectedById(obj.rightChildrens[i],id);
			}
		} else if (obj.type == '016') {
			for (var i = 0; i < obj.childrens.length; i++) {
				loopSetSelectedById(obj.childrens[i],id);
			}
		}
	}
}
